且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查 PowerShell 开关参数是否不存在或错误

更新时间:2023-11-27 22:47:40

要检查参数是否由调用者传入,请检查 $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
}