Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a PowerShell switch parameter is absent or false

Tags:

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?

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?

like image 429
JaapBrasser Avatar asked Jun 28 '19 15:06

JaapBrasser


1 Answers

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
}
like image 89
Mathias R. Jessen Avatar answered Oct 22 '22 11:10

Mathias R. Jessen