Saturday, October 26, 2013

Windows PowerShell: Defining Parameters




You’ll often write a script or function that needs to accept some kind of input. This could be a computer name, a file path or anything like that. You can tell Windows PowerShell to expect these parameters, collect them from the command line, and put their values into variables within your script or function. That makes dealing with input easy and efficient.
You just have to know how to declare your parameters. The simplest means of doing so is the param block:
Param(
  [string]$computerName,
  [string]$filePath
)
You don’t have to break that down into separate lines like I’ve done. It’s legal to run it all together on a single line. I prefer to break it down for easier reading, though. When used as the first lines of code in a script file or within a function, Windows PowerShell reads this and will even tab-complete parameter names when someone runs the script or function. I’ve been careful to use parameter names: they’re –computerName and –filePath here. These are similar to the ones other Windows PowerShell cmdlets use for this kind of information. That way, my parameters are consistent with what’s already in the shell.
If I put this into a script named Get-Something.ps1, I’d use the parameters like this:
./Get-Something –computerName SERVER1 –filePath C:\Whatever
I could also truncate the parameter names. This lets me type fewer characters and they still work:
./Get-Something –comp SERVER1 –file C:\Whatever
I could even omit the names entirely. Windows PowerShell will automatically and positionally accept values. Here I need to be careful to provide values in the same order in which the parameters are listed in my file:
./Get-Something SERVER1 C:\Whatever
Of course, by using parameter names, the command becomes a bit easier for a person to figure out. I then get the luxury of putting the parameters in any order I want:
./Get-Something –filePath C:\Whatever –computerName SERVER1
Windows PowerShell also provides a more complex way of declaring parameters. This more full-fledged syntax lets you define parameters as mandatory, specify a position (if you don’t do so, then the parameter can only be used by name) and more. This expanded syntax is also legal in both scripts and functions:
[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
   [string]$computerName,
       
   [Parameter(Mandatory=$True)]
   [string]$filePath
)
Again, you can run all that together on a single line, but breaking it down makes it a bit easier to read. I’ve given both of my parameters a [Parameter()] decorator, and defined them both as mandatory.

Featured Posts

Adding Accesspolicy to KeyVault for Service Principal Using Portal and Powershell

  Scripts path : https://drive.google.com/drive/folders/1sbBpnVFgXhUIXLdf2E9heyWDeU2f9427?usp=sharing  Adding Accesspolicy to KeyVault for S...