获取传递给PowerShell中的函数的所有参数

use*_*477 3 powershell powershell-2.0 windows-scripting powershell-3.0

我有一个功能如下.它根据传递的参数生成一个字符串.

function createSentenceAccordingly {
Param([Parameter(mandatory = $false)] [String] $name,
      [Parameter(mandatory = $false)] [String] $address,
      [Parameter(mandatory = $false)] [String] $zipcode,
      [Parameter(mandatory = $false)] [String] $city,
      [Parameter(mandatory = $false)] [String] $state)

    $stringRequired = "Hi,"

    if($name){
        $stringRequired += "$name, "
    }
    if($address){
        $stringRequired += "You live at $address, "
    }
    if($zipcode){
        $stringRequired += "in the zipcode:$zipcode, "
    }
    if($name){
        $stringRequired += "in the city:$city, "
    }
    if($name){
        $stringRequired += "in the state: $state."
    }

    return $stringRequired
}
Run Code Online (Sandbox Code Playgroud)

所以,基本上函数会根据传递的参数返回一些东西.我想尽可能地避免if循环并立即访问所有参数.

我可以访问数组或散列映射中的所有参数吗?因为我应该使用命名参数,所以不能在这里使用$ args.如果我可以一次访问所有参数(可能在$ args或hashamp之类的数组中),我的计划是使用它来动态创建返回字符串.

在将来,函数的参数将增加很多,我不想继续写每个附加参数的循环.

提前致谢, :)

bri*_*ist 7

$PSBoundParameters变量是一个哈希表,它只包含显式传递给函数的参数.

您想要的更好的方法可能是使用参数集,以便您可以命名特定的参数组合(不要忘记在这些集合中强制使用相应的参数).

然后你可以这样做:

switch ($PsCmdlet.ParameterSetName) {
    'NameOnly' {
        # Do Stuff
    }
    'NameAndZip' {
        # Do Stuff
    }
    # etc.
}
Run Code Online (Sandbox Code Playgroud)