加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-14 05:44:44 所属栏目:Windows 来源:网络整理
导读:我有一个功能如下.它根据传递的参数生成一个字符串. function createSentenceAccordingly {Param([Parameter(mandatory = $false)] [String] $name,[Parameter(mandatory = $false)] [String] $address,[Parameter(mandatory = $false)] [String] $zipcode,[
我有一个功能如下.它根据传递的参数生成一个字符串.

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.
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读