No difference between IsPresent and explicit cast operator in a function
When using a switch parameter, there is no difference between using IsPresent
or reliying on the explicit cast operator of a [switch]
parameter, both evaluate to either True
or False
:
$p1 = new-object System.Management.Automation.SwitchParameter
$p2 = new-object System.Management.Automation.SwitchParameter $false
$p3 = new-object System.Management.Automation.SwitchParameter $true
$p1.IsPresent # False
$p2.IsPresent # False
$p3.IsPresent # True
[bool] $p1 # False
[bool] $p2 # False
[bool] $p3 # True
More or less the same thing as above, but using a «real» [switch]
parameter:
function f {
param (
[switch] $p
)
# $p.GetType().FullName # -> System.Management.Automation.SwitchParameter
"{0,-5} {1}" -f $p.IsPresent, [bool] $p
}
f # False False
f -p # True True
f -p:$true # True True
f -p:$false # False False
In order to check if a
[switch
] parameter was explicitly set when the function was invoked,
$psBoundParameters.ContainsKey('p')
needs to be used.