0

下午好

遗憾的是,PowerShell 无法通过 Parameter Types 检测 ParameterSet,例如:如果第二个 Parameter 作为 Int 传递,则选择 ParameterSet1,否则使用 ParameterSet2。

因此我想手动检测传递的参数组合。
是否可以获取传递的参数列表DynamicParam,像这样?:

Function Log {
    [CmdletBinding()]
    Param ()
    DynamicParam {
        # Is is possible to access the passed Parameters?,
        # something like that:
        If (Args[0].ParameterName -eq 'Message') { … }

        # Or like this:
        If (Args[0].Value -eq '…') { … }
    }
    …
}

非常感谢您的帮助和光!
托马斯

4

1 回答 1

0

这个第一个发现是错误的!: “我发现了魔法,通过使用$PSBoundParameters我们可以访问传递的参数。”

这是正确但非常令人失望的答案:
这非常烦人且令人难以置信,但看起来 PowerShell 没有传递有关动态传递的参数的任何信息。

以下示例使用New-DynamicParameter此处定义的函数: 我可以使参数集依赖于另一个参数的值吗?

Function Test-DynamicParam {
    [CmdletBinding()]
    Param (
        [string]$FixArg
    )
    DynamicParam {
        # The content of $PSBoundParameters is just 
        # able to show the Params declared in Param():
        # Key     Value
        # ---     -----
        # FixArg  Hello

        # Add the DynamicParameter str1:
        New-DynamicParameter -Name 'DynArg' -Type 'string' -HelpMessage 'DynArg help'

        # Here, the content of $PSBoundParameters has not been adjusted:
        # Key     Value
        # ---     -----
        # FixArg  Hello
    }
    Begin {
        # Finally - but too late to dynamically react! -
        # $PSBoundParameters knows all Parameters (as expected):
        # Key     Value
        # ---     -----
        # FixArg  Hello
        # DynArg  World
    }
    Process {
        …
    }
}

# Pass a fixed and dynamic parameter
Test-DynamicParam -FixArg 'Hello' -DynArg 'World'
于 2018-11-17T16:56:33.353 回答