Skip to content

Checking For Switch Existance

Tags: powershell


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

Terminal window
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
}

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
}

Sources:
  • https://stackoverflow.com/questions/56809557/how-to-check-if-a-powershell-switch-parameter-is-absent-or-false