简体   繁体   中英

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

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
}

You can use PSBoundParameter to check

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'
   }
}

在此输入图像描述

If you have a parameter that can be $true , $false or unspecified, then you might not want the [Switch] parameter type because it can only be $true or $false ( $false is the same as unspecified). As an alternative, you can use a nullable boolean parameter. Example:

function Test-Boolean {
  param(
    [Nullable[Boolean]] $Test
  )

  if ( $Test -ne $null ) {
    if ( $Test ) {
      "You specified -Test `$true"
    }
    else {
      "You specified -Test `$false"
    }
  }
  else {
    "You did not specify -Test"
  }
}

even simpler:

function test{
 [CmdletBinding()]
  param(
  [Parameter(Mandatory=$False,Position=1)][switch]$set
  )
 write-host "commence normal operation"
 if(-not $set){"switch is not set, i execute this"}
 else{"switch is set"}
}

output enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM