PowerShell 可以根据数据类型匹配自动地绑定参数。以下是一个体现该特性的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function Test-Binding { [CmdletBinding(DefaultParameterSetName='Date')] param ( [Parameter(ParameterSetName='Integer', Position=0, Mandatory=$true)] [int] $Id,
[Parameter(ParameterSetName='String', Position=0, Mandatory=$true)] [string] $Name,
[Parameter(ParameterSetName='Date', Position=0, Mandatory=$true)] [datetime] $Date )
$chosenParameterSet = $PSCmdlet.ParameterSetName Switch ($chosenParameterSet) { 'Integer' { 'User has chosen Integer' } 'String' { 'User has chosen String' } 'Date' { 'User has chosen Date' } }
[PSCustomObject]@{ Integer = $Id String = $Name Date = $Date } }
|
现在用户可以测试 Test-Binding
并且提交参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| PS C:\> Test-Binding "Hello" User has chosen String
Integer String Date ------- ------ ---- 0 Hello
PS C:\> Test-Binding 12 User has chosen Integer
Integer String Date ------- ------ ---- 12
PS C:\> Test-Binding (Get-Date) User has chosen Date
Integer String Date ------- ------ ---- 0 11/21/2017 11:44:33 AM
|