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

PowerShell中DynamicParameter类型Switch参数如何判断是否传入

问题原因

PowerShell不会为动态定义的参数自动创建同名的局部变量,所以你直接在代码中调用$Add实际是空值,自然无法获取IsPresent属性。

解决方法

有两种常用的实现方式:

方法1:使用$PSBoundParameters判断(推荐)

PowerShell会把所有传入的参数都存到自动变量$PSBoundParameters字典中,你只需要判断指定的动态参数名是否存在于该字典中即可,效果等价于静态Switch的IsPresent判断:

Process {
    # 判断是否传入了-Add参数
    $PSBoundParameters.ContainsKey('Add')
    # 判断是否传入了-Remove参数
    # $PSBoundParameters.ContainsKey('Remove')
}

方法2:手动绑定动态参数到局部变量

如果你想要和静态参数完全一致的使用习惯,可以手动将动态参数的值赋值给局部变量:

Process {
    $Add = if ($PSBoundParameters.ContainsKey('Add')) { $PSBoundParameters['Add'] } else { [switch]$false }
    $Add.IsPresent
}
修改后的完整测试代码
Function Test-DynamParam {
    Param (
        # Input Parameters
        [Parameter(Mandatory = $false,
                   HelpMessage='Enter. Workflow. Name.')]
        [Alias('OMB','MailBox')]
        [string]$Workflow,

        [Parameter(Mandatory = $false)]
        [Alias('EDIPI','DisplayName')]
        [string[]]$UserName

    )

      DynamicParam {
        if ($Workflow -ne $null -and $UserName -ne $null) {
          $parameterAttribute = [System.Management.Automation.ParameterAttribute]@{
              ParameterSetName = "AddingMembers"
              Mandatory = $false
          }

          $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
          $attributeCollection.Add($parameterAttribute)

          $dynParam1 = [System.Management.Automation.RuntimeDefinedParameter]::new(
            'Add', [switch], $attributeCollection
          )

          $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
          $paramDictionary.Add('Add', $dynParam1)
          

          $parameterAttribute1 = [System.Management.Automation.ParameterAttribute]@{
              ParameterSetName = "RemovingMembers"
              Mandatory = $false
          }

          $attributeCollection1 = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
          $attributeCollection1.Add($parameterAttribute1)

          $dynParam11 = [System.Management.Automation.RuntimeDefinedParameter]::new(
            'Remove', [switch], $attributeCollection1
          )

          $paramDictionary.Add('Remove', $dynParam11)
          return $paramDictionary

        }
      }

    Process {    
        $PSBoundParameters.ContainsKey('Add')
    }
}

调用Test-DynamParam -Workflow 'd' -UserName 'a' -Add会直接返回True,符合预期。

内容的提问来源于stack exchange,提问作者Abraham Zinala

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:12:02