[英]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 $true
,则它应该不返回任何内容。 myFunc - IsLightOn $False
should return "Light off". myFunc - IsLightOn $False
应该返回“Light off”。 However, not specifying true or false for IsLightOn
parameter should default the variable to true and thus return nothing 但是,不为
IsLightOn
参数指定true或false应该将变量默认为true,因此不返回任何内容
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. 当指定值但是我不知道如何将
IsLightOn
默认为true时,一切都有效。
As the others have stated, the Switch parameter type is probably what you want. 正如其他人所说,Switch参数类型可能就是你想要的。 Typically, though, the switch is used to specify non-default behavior (so the default value is $false if the switch parameter is not provided).
但是,通常,交换机用于指定非默认行为(因此,如果未提供switch参数,则默认值为$ false)。 So you could do something similar to what TheIncorrigible1 said:
所以你可以做类似TheIncorrigible1所说的:
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:
您可以在Param()块中设置默认值,如下所示:
function myFunc {
param(
[bool]$IsLightOn = $true
)
if ($IsLightOn -EQ $false){ Write-Host "Light off" }
}
What you're looking for is the [switch]
type: 您正在寻找的是
[switch]
类型:
function Set-LightStatus {
param(
[switch] $On
)
if (-not $On.IsPresent) {
'Light off'
}
}
Use default value in param like : 在param中使用默认值,如:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.