如何检查PowerShell开关参数是否缺失或为false

Jaa*_*ser 3 powershell

我正在构建一个构建哈希表的PowerShell函数。我正在寻找一种可以使用switch参数指定为不存在,正确或错误的方法。我该如何确定?

我可以通过使用[boolean]参数来解决此问题,但是我没有找到一个很好的解决方案。或者,我也可以使用两个开关参数。

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

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

    if ($AddHash) {
        $requestparams.Code = $true
    }
Run Code Online (Sandbox Code Playgroud)

当指定false时如何显示为false,而未指定switch参数时如何显示呢?

Mat*_*sen 9

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

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 
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*eis 4

您可以使用PSBoundParameter来检查

PS C:\ > function test-switch {
   param (
    [switch]$there = $true
   )
   if ($PSBoundParameters.ContainsKey('there')) {
       if ($there) {
          'was passed in'
       } else {
          'set to false'
       }
   } else {
       'Not passed in'
   }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述