本文介绍PowerShell自定义函数中使用参数集时,怎么设置系统自动识别参数的数据类型。 识别参数类型的一个好处就是,在使用参数集时,不需要每次都指定参数名称了。 请看下面这个Test-Binding函数。这个PowerShell函数在设置参数集的时候,为参数集中的第一个参数设置了数据类型,这样在调用函数时,就可以自动判断一个参数值它应该赋给哪个参数了。 复制代码 代码如下: function Test-Binding { [CmdletBinding(DefaultParameterSetName="Name")] param( [Parameter(ParameterSetName="ID", Position=0, Mandatory=$true)] [Int] $id, [Parameter(ParameterSetName="Name", Position=0, Mandatory=$true)] [String] $name ) $set = $PSCmdlet.ParameterSetName “You selected $set parameter set” if ($set -eq ‘ID") { “The numeric ID is $id” } else { “You entered $name as a name” } }
注意函数中参数$id上面的[int]和参数$name上面的[String]。有这了这样的函数定义,那我们在调用时就方便了,如果传一个字符串给它,它会把这个参数当作是$name,而传一个数字给它,这个参数会被当作是$id。且看如下调用函数的示例。 复制代码 代码如下: PS> Test-Binding -Name hallo You selected Name parameter set You entered hallo as a name PS> Test-Binding -Id 12 You selected ID parameter set The numeric ID is 12 PS> Test-Binding hallo You selected Name parameter set You entered hallo as a name PS> Test-Binding 12 You selected ID parameter set The numeric ID is 12