How to Use PowerShell If Statements to Add Conditional Logic to Your Scripts

Last Update: Dec 03, 2024 | Published: Jul 28, 2023

PowerShell

SHARE ARTICLE

PowerShell is a powerful scripting language for many reasons. One such reason is its support for conditional logic, which can help you supercharge your PowerShell scripts to make them even more efficient and effective. In this article, I’m going to teach you how to use If, Else, and Elseif conditional logic and explain how this can help you as a PowerShell scriptwriter.

How to use the PowerShell If statement

PowerShell If statements are used to perform the conditional execution of code. They allow you to test a condition and execute different blocks of code based on whether the condition evaluates to true or false.

Let’s start with two examples showing how to use PowerShell If statements.

Example 1: Checking if a number is positive or negative

In the following example, we have a variable, $number, set to 10. The If statement checks whether the value of $number is greater than 0 using the -gt operator.

  • When the condition is true, it executes the block of code within the first set of curly braces, which in this case prints “The number is positive.”
  • When the condition is false, it moves to the Elseif block and checks if the number is less than 0 using the -lt operator.
  • If the condition is true, it executes the code within the second set of curly braces, printing “The number is negative.”
  • If both conditions are false, it executes the code within the else block, printing “The number is zero.”
$number = 10

if ($number -gt 0) {
    Write-Host “The number is positive.”
} elseif ($number -lt 0) {
    Write-Host “The number is negative.”
} else {
    Write-Host “The number is zero.”
}
Using a PowerShell If statement to check if a number is positive or negative
Checking if a number is positive or negative (Image credit: Petri/Bill Kindle)

Example 2: Checking if a file exists

In this next example, we have a variable, $file, set to the path of a file. The If statement uses the Test-Path cmdlet to check if the file exists.

  • If the condition evaluates to true, meaning the file exists, it executes the code within the first set of curly braces, printing “The file exists.”
  • If the condition is false, it executes the code within the else block, printing “The file does not exist.”
$file = “C:\path\to\file.txt”

if (Test-Path $file) {
    Write-Host “The file exists.”
} else {
    Write-Host “The file does not exist.”
}
Using a PowerShell if statement to check if a file exists
Checking if a file exists (Image credit: Petri/Bill Kindle)

These were just two basic examples of how conditional statements work in PowerShell. Let’s move on to the Else statement.

How to use the PowerShell Else statement with the If statement

In PowerShell, you can use the Else statement with the If statement to create conditional logic. It allows you to specify a block of code to be executed when the condition in the If statement is false.

Let me give you two examples showing how to use Else statements in PowerShell.

Example 3: Checking if a variable is greater than a number

In this example, we make several checks:

  • The If statement checks whether the variable $number is greater than 10.
  • If it is, the message “The number is greater than 10” is displayed.
  • If it does not meet the condition, the Else block runs and the message “The number is not greater than 10” is displayed.
$number = 5

if ($number -gt 10) {
    Write-Host “The number is greater than 10.”
}
else {
    Write-Host “The number is not greater than 10.”
}
Checking if a variable is greater than a number
Checking if a variable is greater than a number (Image credit: Petri/Bill Kindle)

Example 4: Comparing the value of a variable with a string

In this example, the If statement compares the value of the $user variable with the string “John”.

  • If they are equal, the message “Welcome, John!” is displayed.
  • If it does not meet the condition, meaning the value of $user is not “John”, the Else block is executed and the message “Access denied. You are not John.” is displayed.
$user = “John”

if ($user -eq “John”) {
    Write-Host “Welcome, John!”
}
else {
    Write-Host “Access denied. You are not John.”
}
Comparing the value of a variable with a string
Comparing the value of a variable with a string (Image credit: Petri/Bill Kindle)

The difference between an If and Else statement lies in the conditions they evaluate and the subsequent actions they execute.

  • An If statement checks a condition and executes code if the condition is true.
  • An Else statement provides an alternative block of code to be executed when the condition in the If statement is false. If the condition in the If statement is true, the Else block does not run.

To summarize, the If statement allows you to execute code based on a specific condition. The Else statement provides a fallback option when the condition is false. By using these statements together, you can create more flexible and robust logic in your PowerShell scripts.

How to use PowerShell ElseIf statements

ElseIf statements are used to create a condition that checks if the preceding If statement or any preceding ElseIf statements evaluate ‘false’. ElseIf statements allow you to test multiple conditions and execute different code blocks based on the evaluation of those conditions. The ElseIf statement is especially useful when you have over two outcomes.

Here are two examples that show the usage of ElseIf statements in PowerShell.

Example 5: Checking a number’s range

In this example, the code checks the value of the $number variable and executes different code blocks based on its range.

  • If the number is less than 10, the first condition is true, and the corresponding message is displayed.
  • If it’s not, we check the next condition using the ElseIf statement. When the number is between 10 and 19 (inclusive), the second condition is true, and the corresponding message is displayed.
  • If neither of the previous conditions are true, the Else block executes, displaying a message showing that the number is 20 or greater.
$number = 25

if ($number -lt 10) {
    Write-Host “The number is less than 10.”
}
elseif ($number -ge 10 -and $number -lt 20) {
    Write-Host “The number is between 10 and 19.”
}
else {
    Write-Host “The number is 20 or greater.”
}
Checking a number’s range
Checking a number’s range (Image credit: Petri/Bill Kindle)

Example 6: Checking a string’s length

In this example, the code examines the length of the $name string and determines its category based on its length.

  • When the name has over 10 characters, the first condition is true, and the corresponding message is displayed.
  • When the first condition is false, we check the next condition using the ElseIf statement. If the name has over 5 characters (but not over 10), the second condition is true, and the corresponding message is displayed.
  • If neither of the previous conditions are true, the Else block executes and displays a message showing that the name is 5 characters or shorter.
$name = “John”

if ($name.Length -gt 10) {
    Write-Host “The name is longer than 10 characters.”
}
elseif ($name.Length -gt 5) {
    Write-Host “The name is between 6 and 10 characters.”
}
else {
    Write-Host “The name is 5 characters or shorter.”
}
Checking a string’s length
Checking a string’s length (Image credit: Petri/Bill Kindle)

Overall, ElseIf statements in PowerShell specify conditions to check when preceding statements evaluate false. They provide a way to handle multiple conditions and execute different code blocks accordingly.

How to use PowerShell AND/OR statements with If statements

In PowerShell, “AND” and “OR” are logical operators used to combine multiple conditions in conditional statements to control the flow of your script. They can be used with If statements to evaluate multiple conditions simultaneously:

Let me provide you with two examples to show their usage and highlight the differences compared to IfElse statements.

Example 7: Using the AND operator

Imagine that you want to use PowerShell to check if a user is an administrator and if their account is currently active. You can use the AND operator to evaluate both conditions simultaneously.

In this example, the script checks if both the $isAdministrator and $isAccountActive variables are true. If both conditions are true, the script prints a message showing that the user is an administrator with an active account. Otherwise, it will print a message showing that either the user is not an administrator, or their account is inactive.

$user = “John”
$isAdministrator = $true
$isAccountActive = $false

if ($isAdministrator -and $isAccountActive) {
    Write-Host “$user is an administrator with an active account.”
} else {
    Write-Host “$user is not an administrator, or their account is inactive.”
}
Checking if a user is an administrator and if their account is currently active
Checking if a user is an administrator and if their account is currently active (Image credit: Petri/Bill Kindle)

Example 8: Using the “OR” operator

Let’s say you want to check if a server is running Windows Server 2016 or Windows Server 2019. With PowerShell, you can use the OR operator to evaluate these conditions.

In this example, the script uses the OR operator to check if the $osVersion variable is equal to either “Windows Server 2016” or “Windows Server 2019”. If the condition evaluates to true, it prints a message showing that the server is running a supported operating system. Otherwise, it prints a message showing that the server is running an unsupported operating system.

$server = “Server01”
$osVersion = “Windows Server 2012”

if ($osVersion -eq “Windows Server 2016” -or $osVersion -eq “Windows Server 2019”) {
    Write-Host “$server is running a supported operating system.”
} else {
    Write-Host “$server is running an unsupported operating system.”
}
Checking if our variable is equal to either Windows Server 2016 or Windows Server 2019
Checking if our variable is equal to either Windows Server 2016 or Windows Server 2019 (Image credit: Petri/Bill Kindle)

Example 9: Comparison with IfElse statements

The AND and OR operators provide a concise way to evaluate multiple conditions simultaneously. They differ from IfElse statements in that the latter only evaluates a single condition at a time. If the condition in an IfElse statement is true, it executes the code block associated with the If statement. Otherwise, it executes the code block associated with the Else statement.

To show this, let’s change Example 1 to use an IfElse statement instead. In this changed example, the script first checks if the user is an administrator. If true, it then checks if the account is active. Depending on the evaluation of each condition, it executes different code blocks.

$user = “John”
$isAdministrator = $true
$isAccountActive = $false

if ($isAdministrator) {
    if ($isAccountActive) {
        Write-Host “$user is an administrator with an active account.”
    } else {
        Write-Host “$user is an administrator, but their account is inactive.”
    }
} else {
    Write-Host “$user is not an administrator.”
}
Comparison with IfElse statements
Comparison with IfElse statements (Image credit: Petri/Bill Kindle)

Using this approach allows granular control over the flow of the script. However, it can cause nested code blocks and increased complexity compared to using logical operators like “AND” and “OR”.

How to use PowerShell here-strings within If statements

In PowerShell, here-strings are used to create multi-line string literals. They are useful when dealing with large blocks of text, or when you need to preserve formatting.

Here-strings, when used within If statements, can compare a string value against a multi-line string. Here’s the syntax for using here-strings within PowerShell If statements:

if ($string -eq @’
    Multi-line
    string
    ‘@)
{
    # Code to execute if the condition is true
}
else
{
    # Code to execute if the condition is false
}

Let me give you two examples to help you better understand how to use here-strings in If statements.

Example 10: Checking for a specific message

Let’s suppose we have a PowerShell script that prompts the user for input, and we want to check if the user entered a specific message, such as “Hello, world!”. We can use a here-string within an if statement to compare the user input against the expected message.

In the following example, the script prompts the user to enter a message, and we store the input in the $userInput variable. The if statement then compares the user’s input against the expected message using a here-string. If the input matches the expected message, it displays the “User entered the correct message” message; otherwise, it displays “User entered a different message.”

$userInput = Read-Host “Enter a message”

if ($userInput -eq @’
Hello, world!
‘@)
{
    Write-Host “User entered the correct message.”
}
else
{
    Write-Host “User entered a different message.”
}
Using here-strings to check for a specific message
Using here-strings to check for a specific message (Image credit: Petri/Bill Kindle)

Example 11: Comparing a script block

Here’s another example where we want to compare a script block with a predefined block of code. We can use here-strings to define the script block and then compare it within an If statement.

In this example, we have two script blocks, $predefinedCode and $userCode. We want to check if the user code matches the predefined code. By using here-strings to define the script blocks, we can compare them within the If statement.

If the user code matches the predefined code, it displays the “The user code matches the predefined code” message; otherwise, it displays “The user code differs from the predefined code.”

$predefinedCode = {
    Write-Host “This is some code.”
    Write-Host “It does something.”
}

$userCode = {
    Write-Host “This is some code.”
    Write-Host “It does something.”
}

if ($userCode -eq $predefinedCode)
{
    Write-Host “The user code matches the predefined code.”
}
else
{
    Write-Host “The user code differs from the predefined code.”
}
Using here-strings to compare a script block
Using here-strings to compare a script block (Image credit: Petri/Bill Kindle)

How to use concatenation within If statements

In PowerShell, you can concatenate strings using the ‘+’ arithmetic operator. To use concatenation within If statements, you construct a new string by combining multiple string variables or literals.

Here are two examples to illustrate the usage of concatenation in PowerShell If statements:

Example 12: Concatenating string variables

In this example, two string variables, $firstName and $lastName, are defined. The If statement checks if both variables have values (i.e., they are not empty strings).

  • If both conditions are true, we concatenate the first name and last name using the + operator, and we store the result in the $fullName variable. We then display the concatenated full name using the Write-Host cmdlet.
  • If either the first name or the last name is missing, we’ll see that the else block runs and displays an appropriate message.
$firstName = “John”
$lastName = “Doe”

if ($firstName -ne ” -and $lastName -ne ”) {
    $fullName = $firstName + “ “ + $lastName
    Write-Host “Full Name: $fullName”
} else {
    Write-Host “First name or last name is missing.”
}
Concatenating string variables
Concatenating string variables (Image credit: Petri/Bill Kindle)

Example 13: Concatenating string literals

In this second example, three variables are defined: $greeting with the value “Hello”, $name with the value “Alice”, and $age with the value 30. The if statement checks if the $name variable has a value using the IsNullorEmpty() method.

  • If true, we create a message that concatenates the greeting, name, and age using the + operator. We store the resulting message in the $message variable and then display it using the Write-Host cmdlet.
  • If the name is missing (empty string), the else block runs and an appropriate error message is displayed.
$greeting = “Hello”
$name = “Alice”
$age = 30

if ([string]::IsNullorEmpty($name) -eq $false){
    $message = $greeting + “, “ + $name + “! Your age is “ + $age + “.”
    Write-Host $message
} else {
    Write-Host “Name is missing.”
}
Concatenating string literals
Concatenating string literals (Image credit: Petri/Bill Kindle)

Overall, these two examples show how concatenation operations allow you to combine strings dynamically based on certain conditions.

How to use connection strings in If statements

Connection strings are commonly used to establish connections to databases or other external systems. These strings contain information about the server, database name, credentials, and other parameters required to establish the connection.

In If statements, you can use connection strings to run certain code blocks based on the success or failure of a connection. Here are two examples that show the usage of connection strings in PowerShell If statements:

Example 14: Checking a database connection

In this example, we define a connection string ($connectionString) that specifies the server name, database name, and credentials. We then create a SqlConnection object using the connection string. Inside the try block, we attempt to open the connection using $connection.Open().

  • If the connection is successful, the code block is executed under the try block, showing a successful connection.
  • If an exception occurs (i.e., connection fails), the code block is executed under the catch block, showing a failed connection.
# Define the connection string
$connectionString = “Server=server_name;Database=db_name;User Id=user_id;Password=password;"

# Create a SqlConnection object using the connection string
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)

# Attempt to establish the connection
try {
    $connection.Open()
   
    # Connection successful
    Write-Host “Connected to the database.”

    # Perform additional operations on the database if needed

    # Close the connection
    $connection.Close()
}
catch {
    # Connection failed
    Write-Host “Failed to connect to the database.”
}
Checking a database connection
Checking a database connection (Image credit: Petri/Bill Kindle)

Example 15: Checking a network connection

In this second example, we define a connection string ($connectionString) that specifies the server’s name and port number. We then create a TcpClient object using the connection string. Inside the try block, we attempt to establish a connection to the server using $tcpClient.Connect(”server_name”, 1234).

  • If the connection is successful, the code block is executed under the try block, showing a successful connection.
  • If an exception occurs (i.e., connection fails), the code block is executed under the catch block, showing a failed connection.
# Define the connection string
$connectionString = “Server=server_name;Port=1234;"

# Create a TcpClient object using the connection string
$tcpClient = New-Object System.Net.Sockets.TcpClient

# Attempt to establish the connection
try {
    $tcpClient.Connect(”server_name”, 1234)
   
    # Connection successful
    Write-Host “Connected to the server.”

    # Perform additional operations if needed

    # Close the connection
    $tcpClient.Close()
}
catch {
    # Connection failed
    Write-Host “Failed to connect to the server.”
}
Checking a network connection
Checking a network connection (Image credit: Petri/Bill Kindle)

These examples above are simplified and assume a successful connection if no exceptions are thrown. In real-world scenarios, it’s important to handle exceptions appropriately. You should use additional error handling and authentication mechanisms based on the specific requirements of your connection.

How to use Break and Continue statements within an If statement

In PowerShell, the Break and Continue statements are used to control the flow of execution within loops and switches. While Break allows you to exit a loop or switch, Continue lets you skip the current iteration and move to the next iteration.

Although these statements are typically used within loops, you can also use them within an If statement to achieve specific behavior. Let’s explore how to use a Break and Continue within If statements with two easy-to-follow examples.

Example 16: Using Break in an If statement

In this example, we have an array of numbers from 1 to 10. We use a Foreach loop to iterate over each number. Within the loop, we check if the current number is equal to 6.

  • If it is, we display a message and then use the break statement to exit the loop.
  • If the number is not equal to 6, we simply display the current number.
  • When the loop encounters the number 6, it breaks out of the loop and the program continues with the subsequent code.
$numbers = 1..10

foreach ($number in $numbers) {
    if ($number -eq 6) {
        Write-Host “Found the number 6. Exiting the loop.”
        break
    }
   
    Write-Host “Current number is: $number”
}
Using Break in an If statement
Using Break in an If statement (Image credit: Petri/Bill Kindle)

Example 17: Using Continue in an If statement

In this example, we again have an array of numbers from 1 to 10. We use a Foreach loop to iterate over each number. First, we check if the current number is 3 or 7.

  • If true; we display a message and then use the Continue statement to skip the current iteration and move to the next one.
  • If the number is not 3 or 7, we display the current number. The loop will continue until we evaluate all the numbers.
$numbers = 1..10

foreach ($number in $numbers) {
    if ($number -eq 3 -or $number -eq 7) {
        Write-Host “Skipping the number $number”
        continue
    }
   
    Write-Host “Current number is: $number”
}
Using Continue in an If statement
Using Continue in an If statement (Image credit: Petri/Bill Kindle)

In both examples, we used If statements to conditionally run certain actions based on specific conditions. The Break statement allowed us to exit the loop or switch entirely, while the Continue statement skipped the remaining code within the current iteration and moved to the next iteration.

How to use hashtables within If statements

In PowerShell, you can use hashtables within If statements to perform conditional checks based on key-value pairs. Hashtables are a collection of key-value pairs where each key is unique.

Here are two examples showing how to use hashtables in PowerShell If statements.

Example 18: Checking if a specific key exists in a hashtable

In this example, we have a hashtable named $myHashtable with three key-value pairs. The If statement checks if the key “Age” exists in the hashtable using the ContainsKey() method. If the key exists, it prints a message saying that the age is present; otherwise, it prints a message stating that the age is not present.

# Create a hashtable
$myHashtable = @{
    “Name” = “John”
    “Age” = 30
    “City” = “New York”
}

# Check if a specific key exists in the hashtable
if ($myHashtable.ContainsKey(”Age”)) {
    Write-Host “Age is present in the hashtable.”
}
else {
    Write-Host “Age is not present in the hashtable.”
}
Checking if a specific key exists in a hashtable
Checking if a specific key exists in a hashtable (Image credit: Petri/Bill Kindle)

Example 19: Checking if a specific value exists in a hashtable

In this example, we again have the same hashtable named $myHashtable. The If statement checks if the value “New York” exists in the hashtable using the ContainsValue() method. If the value exists, it prints a message saying that the city is New York; otherwise, it prints a message stating that the city is not New York.

# Create a hashtable
$myHashtable = @{
    “Name” = “John”
    “Age” = 30
    “City” = “New York”
}

# Check if a specific value exists in the hashtable
if ($myHashtable.ContainsValue(”New York”)) {
    Write-Host “The city is New York.”
}
else {
    Write-Host “The city is not New York.”
}
Checking if a specific value exists in a hashtable
Checking if a specific value exists in a hashtable (Image credit: Petri/Bill Kindle)

How to use arrays in If statements

In PowerShell, we can use arrays in If statements to check for certain conditions and perform specific actions based on those conditions. Here are two examples that show the usage of arrays in If statements.

Example 20: Checking if an array contains a specific value

In this example, we have an array called $numbers that contains a sequence of numbers. The If statement checks if the array contains the value ‘3’ using the -contains operator. If the condition is true, it will output “The array contains the value 3.” Otherwise, it will output “The array does not contain the value 3.”

# Define an array of numbers
$numbers = 1, 2, 3, 4, 5

# Check if the array contains a specific value, e.g., 3
if ($numbers -contains 3) {
    Write-Host “The array contains the value 3.”
} else {
    Write-Host “The array does not contain the value 3.”
}
Checking if an array contains a specific value
Checking if an array contains a specific value (Image credit: Petri/Bill Kindle)

Example 21: Checking if an array is empty

In this example, we have an empty array called $emptyArray. The If statement checks if the array’s length property is equal to 0. If the condition is true, it will output “The array is empty.” Otherwise, it will output “The array is not empty.”

# Define an empty array
$emptyArray = @()

# Check if the array is empty
if ($emptyArray.Length -eq 0) {
    Write-Host “The array is empty.”
} else {
    Write-Host “The array is not empty.”
}
Checking if an array is empty
Checking if an array is empty (Image credit: Petri/Bill Kindle)

How to use Switch statements in PowerShell

In PowerShell, the Switch statement provides a way to perform conditional branching based on the value of a variable or an expression. It allows you to compare a single value against multiple values and execute different code blocks depending on the match.

Here’s an explanation of how to use Switch statements in PowerShell with two easy-to-follow examples.

Example 22: Checking for days of the week

In this example, we have a $day variable that will be whatever day it currently is. The Switch statement checks the value of $day against different cases using the strings “Monday,” “Tuesday,” and so on.

  • If there’s a match, the script executes the corresponding code block.
  • If there’s no match, the script executes the Default block. Here, the output will be “It’s the start of the week!”
$day = (Get-Date).DayOfWeek

switch ($day) {
    “Monday” {
        Write-Host “It’s the start of the week!”
    }
    “Tuesday” {
        Write-Host “It’s Tuesday!”
    }
    “Wednesday” {
        Write-Host “It’s the middle of the week!”
    }
    “Thursday” {
        Write-Host “It’s almost Friday!”
    }
    “Friday” {
        Write-Host “It’s finally Friday!”
    }
    Default {
        Write-Host “It’s the weekend!”
    }
}
image023
Using a Switch statement to check for days of the week (Image credit: Petri/Bill Kindle)

Example 23: Categorizing numbers

In this second example, we have a $number variable with the value 42. The Switch statement checks the value of $number against different cases using script blocks. The first case checks if the number is less than 0, the second case checks if it’s greater than 0, and the Default block runs if no other cases match. Here, the output will be “Positive number.”

$number = 42

switch ($number) {
    { $_ -lt 0 } {
        Write-Host “Negative number”
    }
    { $_ -gt 0 } {
        Write-Host “Positive number”
    }
    Default {
        Write-Host “Zero”
    }
}
Using a Switch statement to categorize numbers
Using a Switch statement to categorize numbers (Image credit: Petri/Bill Kindle)

In both examples, you can customize the code blocks within each case to perform any desired actions based on the matching condition. The Switch statement is a powerful construct in PowerShell that provides an elegant way to handle multiple conditions to run code blocks.

PowerShell and conditional logic: A summary

Overall, If statements and their related constructs provide powerful tools for implementing conditional logic in PowerShell scripts. If statements are essential for performing conditional execution of code as they allow you to test a condition and execute different code blocks based on whether the condition evaluates to true or false.

The examples I provided in this article demonstrated how PowerShell If statements can be used to check if a number is positive or negative, or if a file exists. However, I detailed many other conditional logic tricks in this article to help you become a better PowerShell scriptwriter. The information here was pretty dense, so here is what you need to remember.

  • Else statements are used in conjunction with If statements to create conditional logic, providing a fallback option when the condition is not met.
  • ElseIf statements can also be used to create conditions that are checked only if preceding If or ElseIf statements evaluate to false, allowing for more complex conditional logic.
  • Logical operators such as AND and OR can be utilized to combine multiple conditions in If statements to control the flow of the script. Here-strings can also be used within If statements to compare string values against multi-line strings.
  • The concatenation of strings using the ‘+’ operator also allows you to dynamically combine strings based on specific conditions within If statements.
  • Connection strings are commonly used in If statements to conditionally execute code blocks based on the success or failure of a connection to databases or external systems.
  • The Break and Continue statements provide control over loop and switch execution, and you can use them within If statements to achieve a specific behavior.
  • Hashtables and arrays can also be used in If statements to check for specific conditions and perform actions based on those conditions.
  • Finally, the Switch statement allows for conditional branching based on the value of a variable or expression, enabling the execution of different code blocks depending on the match.

Thank you for reading this detailed guide about PowerShell If statements, feel free to ask any questions in the comment section below!

Table of contents

Table of contents

SHARE ARTICLE