如何在PowerShell的switch语句中获取传入的实际参数?
解决方法
你不需要借助$MyInvocation或$PSCmdlet这类复杂手段,直接使用foreach循环中的迭代变量$MyArgument就能获取当前处理的单个参数值,替换代码里的$parameter即可。
修改后的完整代码
function test { [CmdletBinding()] param ( [Parameter( Mandatory = $true, ParameterSetName = "MyArgument" )] [ValidateSet("Value1", "Value2")] [string[]] $MyArguments ) foreach ($MyArgument in $MyArguments) { switch ($MyArgument) { Value1 { Write-Host "$MyArgument used" } Value2 { Write-Host "$MyArgument used" } } } } test -MyArgument Value1, Value2
运行这段代码后,会依次输出:
Value1 used Value2 used
简化优化
由于你的两个switch分支逻辑完全一致,还可以简化代码:
function test { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = "MyArgument")] [ValidateSet("Value1", "Value2")] [string[]] $MyArguments ) foreach ($MyArgument in $MyArguments) { switch ($MyArgument) { "Value1", "Value2" { Write-Host "$MyArgument used" } } } } test -MyArgument Value1, Value2
甚至因为参数已经通过ValidateSet限制了只能传入Value1或Value2,可以直接去掉switch语句,进一步简化:
function test { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = "MyArgument")] [ValidateSet("Value1", "Value2")] [string[]] $MyArguments ) foreach ($MyArgument in $MyArguments) { Write-Host "$MyArgument used" } } test -MyArgument Value1, Value2
内容的提问来源于stack exchange,提问作者Sanctuary
相关产品推荐
相关产品推荐

