Pass Boolean Parameters to a PowerShell Script From a Command Prompt

A PowerShell script is a collection of commands saved into a text file with the .ps1
extension. PowerShell executes those commands in sequence to perform different actions. You can define parameters in PowerShell using the param
statement.
Here is an example of a simple PowerShell script, myscript.ps1
, which takes the value as input from the user.
param($a,$b)
if($a -lt $b){
Write-Host "$a is less than $b"
}
else{
Write-Host "$a is not less than $b"
}
You can use the command below to pass values and run the above script from a command prompt.
powershell.exe -NoProfile -Command .\myscript.ps1 -a 4 -b 5
Output:
4 is less than 5
As you can see, we were able to pass values to a PowerShell script from a command prompt. We will teach you to pass Boolean
values to a PowerShell script from a command prompt. A Boolean value can be either TRUE
or FALSE
.
Use Boolean Parameter to Pass Boolean Values to a PowerShell Script From a Command Prompt
You can set the data type of your parameter to [bool]
to pass Boolean values to a PowerShell script from a command prompt.
param([int]$a, [bool]$b)
switch($b){
$true {"It is true."}
$false {"It is false."}
}
Boolean parameters accept only Boolean values and numbers, such as $True
, $False
, 1
or 0
.
powershell.exe -NoProfile -Command .\myscript.ps1 -a 1 -b $True
Output:
It is true.
Try False
value:
powershell.exe -NoProfile -Command .\myscript.ps1 -a 5 -b 0
Output:
It is false.
Use the switch
Parameter to Pass Boolean Values to a PowerShell Script From a Command Prompt
A switch
parameter in PowerShell does not take a value. But, it is Boolean
in nature and conveys a Boolean true
or false
value through its presence or absence. So, when a switch parameter is present, it has an actual value. And when a switch parameter is absent, it has a false value. Switch
parameters are easy to use and are preferred over Boolean
parameters, which have a less natural PowerShell syntax.
param ([int] $a, [switch] $b)
switch($b){
$true {"The value is $b."}
$false {"The value is $b."}
}
When the switch parameter is present:
powershell.exe -NoProfile -Command .\myscript2.ps1 -a 5 -b 1
Output:
The value is True.
When the switch parameter is absent:
powershell.exe -NoProfile -Command .\myscript2.ps1 -a 5
Output:
The value is False.