$swth.IsPresent
and $swth
can be used interchangeably, because in a Boolean context (such as an if
conditional) $swth
(an instance of type [switch] https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.switchparameter representing a switch parameter https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-6#switch-parameters) effectively returns the value of the .IsPresent
property.[1]
In fact, $swth
is probably preferable[2], not just for concision, but because the .IsPresent
property is somewhat confusingly named:
.IsPresent
并不表示presence开关本身,但它是否值为$true
.
单独指定开关时 --swth
- 暗示both,如果您明确将其设置为,则情况并非如此$false
:通过-swth:$false
makes .IsPresent
return $false
,即使开关很明显present.
Passing $false
明确地并不常见,但有其用途,例如选择退出确认提示时-Confirm:$false
, 什么时候以编程方式构建论据。
所以,如果你想区分用户没有通过交换机和用户传递它的值$false
, .IsPresent
不会帮助你 - 你必须使用$PSBoundParameters.ContainsKey('swth')
[1] On conversion to Boolean, which happens in method LanguagePrimitives.IsTrue() https://github.com/PowerShell/PowerShell/blob/bbd54c317e01d652081753a9cd2350e96aa8bd3e/src/System.Management.Automation/engine/LanguagePrimitives.cs#L1013, PowerShell calls a [switch]
instance's .ToBool() method https://github.com/PowerShell/PowerShell/blob/bbd54c317e01d652081753a9cd2350e96aa8bd3e/src/System.Management.Automation/engine/MshCmdlet.cs#L108, which in turn returns the private backing variable behind the .IsPresent
property.
[2] The only caveat is that you must be aware that $swth
is not a Boolean ([bool]
), but of type [switch]
, which may matter in other contexts.