You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 05:32:33