【问题标题】:Does a DynamicParameter Switch not read like a Static Parameter [switch]?动态参数开关读起来不像静态参数 [开关]?
【发布时间】:2021-10-31 01:36:17
【问题描述】:

希望标题足够清晰,但是与静态(类型转换)开关相比,我在如何评估 DynamicParameter Switch 方面存在一些问题。

在以下代码块中,有 2 个开关只有在其他 2 个参数不为空和/或不为空时才可用: p>

  • 添加
  • 移除
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 {    
        $Add.IsPresent 
    }
}

跑步:

  • Test-DynamParam -Workflow 'd' -UserName 'a' -Add

返回空。

不幸的是,$Add.IsPresent 不会被评估为任何 boolean 值,无论开关是否存在。然而在这个函数中它是(这很有意义):

Function Test-StaticParam {
    Param (

        [switch]$Add

    )

    $Add.IsPresent

}

跑步:

  • Test-StaticParam -Add

返回True

问题

如何根据所选的动态参数进行评估?

【问题讨论】:

    标签: powershell powershell-5.1


    【解决方案1】:

    使用$PSBoundParameters自动变量:

    Process {    
        $PSBoundParameters['Add'].IsPresent 
    }
    

    【讨论】:

    • 很高兴聪明的人早起!这对我有用。谢谢你!另外,不知道这是$PSBoundParameters 的功能;而是像这样使用它:$PSBoundParameters.ContainsKey('Add') 这并没有给我任何结果。当它允许我时会接受答案。
    • @AbrahamZinala $PSBoundParameters 的好处在于它实现了IDictionary - 所以你可以像对待任何其他字典/哈希表一样对待它:-)
    猜你喜欢
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多