I'd like to understand how a PowerShell script handles boolean parameter values.
I have a script with 4 parameters, 2 of which are boolean variables. When I run the script & set one of these parameters to $False, the script still thinks this variable is set to $True.
Version 1: BooleanTest.ps1 (using BOOLEAN parameters)
param(
[Parameter(Mandatory=$True, Position=1)][string]$param1,
[Parameter(Mandatory=$True, Position=2)][string]$param2,
[Parameter(Mandatory=$True, Position=3)][bool]$param3,
[Parameter(Mandatory=$True, Position=4)][bool]$param4
)
write-output $param1, $param2, $param3, $param4
Running this script from the command prompt returns the following:
>BooleanTest.ps1 -param1 "String1" -param2 "String2" -param3 $True -param4 $False
String1
String2
$True
$True
I've also tried adjusting this script to use switch parameters instead:
Version 2: BooleanTest.ps1 (using SWITCH parameters)
param(
[Parameter(Mandatory=$True, Position=1)][string]$param1,
[Parameter(Mandatory=$True, Position=2)][string]$param2,
[switch]$param3,
[switch]$param4
)
write-output $param1, $param2, $param3, $param4
Running this version from the command prompt returns:
>BooleanTest.ps1 -param1 "String1" -param2 "String2" -param3:$True -param4:$False
String1
String2
IsPresent
---------
True
False
Based on these trials, I have the following questions:
- In Version 1, why is the fourth variable incorrectly being returned as $True when I declared it as $False?
- In Version 2, why is the "IsPresent" list being returned?
- How does the switch statement work? After passing in the variable, do I need to run additional code to assign the True/False value, or can I use the parameter as is?
I've read various several help & troubleshooting articles, but there doesn't seem to be any clear documentation on passing boolean values to a script. I would appreciate any information that would help me understand the proper techniques to apply in this situation.
My System Set-Up:
OS: Windows 10
PowerShell Version: PowerShell 7.1.5
String1 String2 True False
– DivisionIsPresent
thing is interesting, normally you use a switch parameter just like a boolean parameter in code. The difference is just in passing explicit$false
value. E. g. you can useswitch
parameter in boolean context likeif( $param3 ) { ... } else { ... }
– DivisionSwitchParameter
, which implicitly converts to Boolean. – Thicken