Windows PowerShell: Defining Parameters

Sometimes when we are creating console applications, we might want to specify parameters. In this case, we may have to hanle with that by ourselves, to retrive argument from argument list and assign to the corresponding place.

Someone ever asked me the question that do we have a kind of class or library existed already to that for us. The answer is yes of course, however, in a different kind of format - Windows Powershell.

Let's see how does it look like. The content below is from http://technet.microsoft.com/en-us/magazine/jj554301.aspx 


There are simple and complex ways to define parameters in Windows PowerShell, and both ways have their benefits.

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.

If someone tries to run my script and forgets one or both of these parameters, the shell will prompt for them automatically. There’s no extra work on my part needed to make that happen. I’ve also defined –computerName as being in the first position, but –filePath needs to be provided by name.

There are some other advantages to using the [CmdletBinding()] directive. For one, it ensures my script or function will have all the Windows PowerShell common parameters, including –Verbose and –Debug. Now, I can use Write-Verbose and Write-Debug within my script or function, and their output will be suppressed automatically.

Run the script or function with –Verbose or –Debug, and Write-Verbose or Write-Debug (respectively) are magically activated. That’s a great way to produce step-by-step progress information (Write-Verbose) or add debugging breakpoints (Write-Debug) in your scripts.

As they’re currently written, both parameters will accept only a single value. Declaring them as [string[]] would let them accept an entire collection of values. You’d then enumerate this using a Foreach loop, so you could work with one value at a time.

Another neat parameter type is [switch]:

Param([switch]$DoSomething)

Now, I can run my script or function with no –DoSomething parameter and internally the $DoSomething variable will be $False. If I run the script with the –DoSomething parameter, $DoSomething gets set to $True. There’s no need to pass a value to the parameter. Windows PowerShell sets it to $True if you simply include it. This is how switch parameters operate, such as the –recurse parameter of Get-ChildItem.

Keep in mind that each parameter is its own entity, and it’s separated from the next parameter by a comma. You’ll notice that in a previous example:

[CmdletBinding()]
Param(
   [Parameter(Mandatory=$True,Position=1)]
   [string]$computerName,	
   [Parameter(Mandatory=$True)]
   [string]$filePath
)

There the entire –computerName parameter, including its [Parameter()] decorator, appears before the comma. The comma indicates I’m done explaining the first parameter and I’m ready to move on to the next. Everything associated with –filePath follows the comma. If I needed a third parameter, I’d put another comma:

[CmdletBinding()]
Param(
   [Parameter(Mandatory=$True,Position=1)]
   [string]$computerName,	
   [Parameter(Mandatory=$True)]
   [string]$filePath,
   [switch]$DoSomething
)

All of that is contained within the Param() block. Note that you don’t have to use the [Parameter()] decorator on every parameter. Only use it on the ones where you need to declare something, such as the parameter being mandatory, accepting pipeline input, being in a certain position and so on. Run help about_functions_advanced_parameters in Windows PowerShell for more information on other attributes you can declare that way.

Writing functions and scripts that accept input only via parameters is a best practice. It makes them more self-contained, easier to document and more consistent with the way the rest of the shell works.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值