Boolean Values in PowerShell

In Windows PowerShell scripts, we often use logic based on something true.
But there may be situations where you need to handle the inverse. That is situations where you need to know when something does not meet some criteria.
So while writing and debugging, PowerShell takes a more positive approach. It is essential to understand negation.
Therefore, this article is vital to discuss how Boolean works in Windows PowerShell.
Definition of Boolean in Windows PowerShell
When deciding if something is or isn’t in PowerShell, we talk about Boolean values represented as $True
or $False
.
The basic syntax shown below explains how Boolean works. Boolean type values are forms of output that return either True
or False
.
Still, the syntax uses the comparison and conditional operators to compare the two or multiple values.
Example Code:
"yes" -eq "yes"
"no" -ne "no"
Output:
True
False
When evaluating the Boolean expression, it compares the left side of the value to the right side of the value. If the value of the left side is equal to the value of the right side, then it is evaluated as True
otherwise False
, as shown above.
There are multiple ways to output a Boolean value, and we will discuss them in the next section of the article.
Using Comparison Operators
We can use multiple conditional operators to compare values and output a Boolean result as our first example.
Example Code:
10 -eq 10 # equal
10 -gt 20 # greater than
10 -lt 20 # less than
10 -le 11 # less than or equal
10 -ge 8 # greater than or equal
Output:
True
False
True
True
True
Using PowerShell Commands
Some native Windows PowerShell commands return Boolean values. One example of this is the Test-Path
cmdlet. The Test-Path
cmdlet checks if the directory path exists inside our local machine.
Example Code:
Test-Path C:\Windows\temp
Output:
True
Some native commands will require a parameter to output a Boolean value. For example, the Test-Connection
command uses the -Quiet
parameter to return a Boolean value.
Example Code:
Test-Connection www.google.com -Count 2 -Quiet
Output:
True
Boolean types (True
and False
) are beneficial while working with the scripts. While writing scripts, programmers need to evaluate the previous output and move to the following commands if they are true or false. It also helps to create a flow chart properly for scripts.
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn