简体   繁体   中英

Is there a way in Powershell for a boolean parameter to automatically be true if not specified when the function is called?

If the function is called myFunc -IsLightOn $true , it should return nothing. myFunc - IsLightOn $False should return "Light off". However, not specifying true or false for IsLightOn parameter should default the variable to true and thus return nothing

function myFunc{
   Param(
    [bool]$IsLightOn
   ) if ($LightIsOn -EQ $false){
      Write-Host "Light off"
   }
}

Everything works when the value is specified but I don't know how to default IsLightOn to true.

As the others have stated, the Switch parameter type is probably what you want. Typically, though, the switch is used to specify non-default behavior (so the default value is $false if the switch parameter is not provided). So you could do something similar to what TheIncorrigible1 said:

function Set-LightStatus {
    param(
        [switch] $Off
     )

    if ($Off) {
        'Light off'
    }  
}

If you want exactly what you asked for in the question, though, you can continue to use a Boolean parameter value. You can set defaults in the Param() block, like so:

function myFunc {
  param(
    [bool]$IsLightOn = $true
)
  if ($IsLightOn -EQ $false){ Write-Host "Light off" }  
}

What you're looking for is the [switch] type:

function Set-LightStatus {
    param(
        [switch] $On
    )

    if (-not $On.IsPresent) {
        'Light off'
    }
}

Use default value in param like :

function myFunc{
    Param(
        [bool]$IsLightOn=$true # Default value
    ) 

    if (!$IsLightOn) { # CHECKING THE VALUE
        Write-Host "Light off" # PRINTING ON THE HOST
    } # END OF IF

} # END OF FUNCTION

myFunc # WITHOUT PASSING VALUE
myFunc -IsLightOn:$true # PASSING TRUE VALUE
myFunc -IsLightOn:$false # PASSING FALSE VALUE

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