如何检查 PowerShell 开关参数是否不存在或错误 [英] How to check if a PowerShell switch parameter is absent or false

查看:191
本文介绍了如何检查 PowerShell 开关参数是否不存在或错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个用于构建哈希表的 PowerShell 函数.我正在寻找一种方法,我可以使用开关参数指定为不存在、真或假.我如何确定这一点?

I am building a PowerShell function that builds a hash table. I am looking for a way I can use a switch parameter to either be specified as absent, true or false. How can I determine this?

我可以通过使用 [boolean] 参数来解决这个问题,但我没有发现这是一个优雅的解决方案.或者,我也可以使用两个开关参数.

I can resolve this by using a [boolean] parameter, but I didn't find this an elegant solution. Alternatively I could also use two switch parameters.

function Invoke-API {
    param(
        [switch]$AddHash
    )

    $requestparams = @{'header'='yes'}

    if ($AddHash) {
        $requestparams.Code = $true
    }

在指定 false 时如何让它显示 false 而在未指定 switch 参数时不显示任何内容?

How would I get it to display false when false is specified and nothing when the switch parameter isn't specified?

推荐答案

要检查参数是否由调用者传入,请检查 $PSBoundParameters 自动变量:

To check whether a parameter was either passed in by the caller or not, inspect the $PSBoundParameters automatic variable:

if($PSBoundParameters.ContainsKey('AddHash')) {
    # switch parameter was explicitly passed by the caller
    # grab its value
    $requestparams.Code = $AddHash.IsPresent
}
else {
    # parameter was absent from the invocation, don't add it to the request 
}

<小时>

如果您要传递多个开关参数,请遍历 $PSBoundParameters 中的条目并测试每个值的类型:


If you have multiple switch parameters that you want to pass through, iterate over the entries in $PSBoundParameters and test the type of each value:

param(
  [switch]$AddHash,
  [switch]$AddOtherStuff,
  [switch]$Yolo
)

$requestParams = @{ header = 'value' }

$PSBoundParameters.GetEnumerator() |ForEach-Object {
  $value = $_.Value
  if($value -is [switch]){
    $value = $value.IsPresent
  }

  $requestParams[$_.Key] = $value
}

这篇关于如何检查 PowerShell 开关参数是否不存在或错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆