Reputation: 21
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.
Upvotes: 1
Views: 3289
Reputation: 989
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
Upvotes: 1
Reputation: 1666
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" }
}
Upvotes: 3
Reputation: 19664
What you're looking for is the [switch]
type:
function Set-LightStatus {
param(
[switch] $On
)
if (-not $On.IsPresent) {
'Light off'
}
}
Upvotes: 1