Comparison Operators and Conditional Logic in PowerShell

Hello Everyone,

In this blog will explore about Comparison Operators and Conditional Logic in PowerShell.

System administrators make decisions daily regarding what maintenance tasks to perform on servers based on numerous criteria. Automating repetitive administrative tasks with PowerShell frequently involves using logic to replicate this decision-making process. Several techniques can be used to achieve the desired results using comparisons, filters, and conditional logic.

PowerShell comparison operators

You won’t get far in creating PowerShell scripts without performing conditional logic, which begins with comparing values. The ability to check if a user exists, if a file has been created, or if one computer is able to connect to another all require a comparison to a value. The one big gotcha in PowerShell has to do with syntax: rather than using traditional comparison operators like < or > PowerShell uses -lt or -gt to perform comparisons.

Several comparison operators are most commonly used with numerical values, although they have their place when working with dates or version numbers and other variable types as well. The following table contains the comparison operators most commonly used to compare numbers.

When comparing against text strings -eq can be used when an exact match is required. The -match operator can be used when looking for a portion of a string, or -like can be used to perform wildcard searches. PowerShell can also be used to search for a particular value within an array by using -in , -notin , -contains , or -notcontains .

In cases where more than one condition must be met, parenthetical statements can be used in order to manage groups of conditions. The following example can be used to select processes related to various web browsers:

Get-Process | Where-Object {($.Name -eq “iexplore”) -or ($.Name -eq “chrome”) -or ($_.Name -eq “firefox”)}

PowerShell Where-Object

Many common PowerShell cmdlets return a long list of values which are of little use as a whole. Using Where-Object allows you to quickly limit the results to the conditions you define within a ScriptBlock . The following example lists files in the current user’s profile which have the archive bit set:

Get-ChildItem $env:USERPROFILE -Recurse -Force | Where-Object {$_.Mode -like “a”}

This example shows the use of the $_ default variable, which is used to indicate the current record being passed from the pipeline. PowerShell 4 allows you to use Where-Object using aliases such as ? or Where , and accepts shortcut notation for the condition as well. This example is functionally identical to the one above:

Get-ChildItem $env:USERPROFILE -Recurse -Force | ? Mode -like “a

If, elseIf, and else statements

One of the more common methods of controlling the flow of your script and performing conditional logic is through if statements. By setting first the criteria to be met, and then the action to be taken, IT pros can automate complex administrative actions. In PowerShell, as in most programming languages, if statements can be used with elseif and else statements, which allow you to handle multiple scenarios.

A simple if statement requires the if keyword, followed by the condition in parentheses. When the condition evaluates as true the code contained within the ensuing script block is then processed; if false it is simply skipped. The following example shows a simple if statement that tests for internet connectivity:

if (Test-Connection google -Quiet) { Write-Host “Internet connection is live.” }

With the elseif statement you can add additional conditions to a single if statement. This differs from multiple if statements in that only the first condition met will be used. Else statements are placed at the end of an if statement to perform an action if none of the previous conditions are met. An example of a more complex condition with if , elseif , and else blocks is below:

if (Test-Connection google -Quiet) { Write-Host “Internet connection is live.” } elseif (Test-Connection -Quiet) { Write-Host “Only local network connectivity is available.” } else { Write-Host “Network connectivity is unavailable.” }

Switch statements

Like if statements, switch allows you to perform a set of commands when certain criteria are met. The big difference between if and switch is that switch statements evaluate a single set of criteria against multiple possibilities, rather than each statement evaluating a potentially unrelated set of criteria.

Switch statements begin with the switch keyword followed by the expression to be evaluated. A scriptblock enclosed in curly brackets follows the evaluated expression and contains the potential matches to be acted against. Each of these matches is followed by a scriptblock, which defines the actions to be taken when the condition is met. In order to perform actions against unmatched criteria the default keyword can be used. This example uses the Get-Date cmdlet to read the day of the week and returns whether it is a Weekday or the Weekend:

switch ((Get-Date).DayOfWeek) { “Saturday” {“Weekend”} “Sunday” {“Weekend”} Default {“Weekday”} }

The previous example can be further simplified by using the -Wildcard option as shown below. Using wildcards with switch statements gives you a more efficient method of performing conditional actions.

switch -Wildcard ((Get-Date).DayOfWeek) { "S" {“Weekend”} Default {“Weekday”} }*