0

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

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

  • 添加
  • 消除
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都不会评估为任何布尔值。然而在这个函数中它是(这是有道理的):

Function Test-StaticParam {
    Param (

        [switch]$Add

    )

    $Add.IsPresent

}

跑步:

  • Test-StaticParam -Add

返回True

问题

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

4

1 回答 1

2

使用$PSBoundParameters自动变量:

Process {    
    $PSBoundParameters['Add'].IsPresent 
}
于 2021-09-01T14:28:09.717 回答