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?
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
}
How would I get it to display false when false is specified and nothing when the switch parameter isn't specified?
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With