我有一个功能如下.它根据传递的参数生成一个字符串.
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 }
所以,基本上函数会根据传递的参数返回一些东西.我想尽可能地避免if循环并立即访问所有参数.
我可以访问数组或散列映射中的所有参数吗?因为我应该使用命名参数,所以不能在这里使用$args.如果我可以一次访问所有参数(可能在$args或hashamp之类的数组中),我的计划是使用它来动态创建返回字符串.
在将来,函数的参数将增加很多,我不想继续写每个附加参数的循环.
提前致谢,:)
解决方法
$PSBoundParameters
variable是一个哈希表,它只包含显式传递给函数的参数.
您想要的更好的方法可能是使用parameter sets,以便您可以命名特定的参数组合(不要忘记在这些组中强制使用相应的参数).
然后你可以这样做:
switch ($PsCmdlet.ParameterSetName) { 'NameOnly' { # Do Stuff } 'NameAndZip' { # Do Stuff } # etc. }