Back to Basics: Conditional Logic with PowerShell If

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

In this article, I will start with some basics about conditional logic in PowerShell. I’ll also discuss the syntax for loops and how to iterate through a list of values. Lastly, there will be an example discussing how you can use your resourcefulness when writing scripts that interact with external APIs.

The “powershell if else do nothing” is a PowerShell cmdlet that allows users to create conditional logic with the If keyword. The If keyword allows for one of two possible outcomes, which are based on whether or not a condition is met.

Back to Basics: Conditional Logic with PowerShell If

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Set percentage-based criteria. $Critical = $$$$$$$ $Warning = 70$$$$$$$ # Find out all there is to know about Fixed Disk. Where-Object $diskObj = Get-CimInstance -ClassName CIM LogicalDisk

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType # Create a new empty array to contain the final results. @$finalReport$finalReport$finalReport$finalReport$final () # Go through each disk’s information one by one. $diskObj.foreach( # Determine the proportion of free space. [int] $percentFree ((

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.Size) * 100) ((

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.Size)) ((

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace / # If ($percentFree -gt $Warning) $Status = ‘Normal,’ determine the “Status.” $Status = ‘Warning’ elseif ($percentFree -gt $Critical) if ($percentFree -le $Critical) is false $Status =’Critical’ $Status =’Critical’ $Status =’Critical’ $Status = # Assemble the attributes of the object you want to include in the report. $tempObj = [ordered] $tempObj = [ordered] $tempObj = [ @

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DeviceID = ‘Drive Letter’

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.VolumeName = ‘Drive Name’ ‘Total Space (GB)’ = [int] ‘Total Space (GB)’ = [int] ‘Total Space (GB (1 GB /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.Size) [int] ‘Free Space (GB)’ = (1 GB /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace) ‘Free Space (percentage)’ equals “01” -f [int] -f [int] -f [int] ‘Status’ = $Status, $percentFree,’percent ‘ # Include the item in your final report. $finalReport += New-Object psobject -property $tempObj $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalRe

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Set percentage-based criteria. $Critical = $$$$$$$ $Warning = 70$$$$$$$ # Find out all there is to know about Fixed Disk. Where-Object $diskObj = Get-CimInstance -ClassName CIM LogicalDisk

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType # Create a new empty array to contain the final results. @$finalReport$finalReport$finalReport$finalReport$final () # Go through each disk’s information one by one. $diskObj.foreach( # Determine the proportion of free space. [int] $percentFree ((

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.Size) * 100) ((

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.Size)) ((

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace / # If ($percentFree -gt $Warning) $Status = ‘Normal,’ determine the “Status.” $Status = ‘Warning’ elseif ($percentFree -gt $Critical) if ($percentFree -le $Critical) is false $Status =’Critical’ $Status =’Critical’ $Status =’Critical’ $Status = # Assemble the attributes of the object you want to include in the report. $tempObj = [ordered] $tempObj = [ordered] $tempObj = [ @

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DeviceID = ‘Drive Letter’

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.VolumeName = ‘Drive Name’ ‘Total Space (GB)’ = [int] ‘Total Space (GB)’ = [int] ‘Total Space (GB (1 GB /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.Size) [int] ‘Free Space (GB)’ = (1 GB /

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Where-Object

Scripts have the ability to make judgments. How? By using the idea of conditional logic. The if statement in PowerShell and the if/else constructs are often used to establish conditions.

You develop PowerShell scripts with a particular purpose or set of tasks in mind. However, depending on one or more criteria, an operation may have several alternative actions. In this case, the PowerShell If-Else construct comes in handy.

In this article, you’ll discover what the If-Else construct in PowerShell is, how it works, and how to use it. You’ll also discover some of the numerous ways you can utilize PowerShell If-Else to add conditional logic handling to your scripts from the examples.

Understanding the If-Else Syntax in PowerShell

The if-else component in PowerShell evaluates one or more conditional statements. The If statement syntax is shown below. Flow control is a term used to describe this method.

if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}]

Each test is contained in a parenthesis, as you can see from the syntax above (). Different operators, such as comparison operators and logical operators, may be used in tests.

The statement lists contain the code that will be executed if the test result is true.

Then, in an If statement group, there are three potential statements. The IF, ELSEIF, and ELSE statements are used in this example.

  • The first test to evaluate is in the if statement, followed by the first statement list contained in curly brackets. The only statement that must be included is the PowerShell if statement.
  • You add conditions to the elseif statement. When you have several criteria, you may use multiple ElseIf statements. Each of these criteria will be evaluated in turn by PowerShell.
  • The otherwise statement does not take any conditions into account. This statement’s statement list includes the code to execute if all of the previous conditions are false.

Understanding the If-Else Logic Flow in PowerShell

You should acquaint yourself with the logic flow of the PowerShell If-Else to have a better understanding of how it works. The flow of the PowerShell If-Else statement is shown in the figure below.

If-Else Logic Flow in PowerShellIf-Else Logic Flow in PowerShell

When the if statement is executed, PowerShell evaluates each condition to see whether it returns true or false. The following is an overview of the behavior:

  • The condition in Test 1 is evaluated by PowerShell.
  • If Test 1 returns true, PowerShell executes the code within the If statement list before exiting the If statement.
  • PowerShell proceeds to analyze the condition (Test n) in the following ElseIf statement if the result of Test 1 is false.
  • If the result of Test n is false, PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next ElseIf statement, if another ElseIf statement exists -OR- PowerShell continues to evaluate the condition (Test n) in the next
  • If Test n returns false, the code in the Else expression is executed. The If statement -OR- will then be exited by PowerShell.
  • The code in the ElseIf expression executes if the result of Test n is true. The If statement will then be exited by PowerShell.

Using the If-Else Statement in PowerShell

Several examples of how to utilize the PowerShell If-Else statement in scripts are provided in the following sections. If you ever find yourself in a scenario where you need to utilize the If statement, the skills you’ll learn may help you do so.

There is just one If-Else condition.

The single If statement is the most fundamental. When there is just one condition to test, you should use a single if statement.

The example below checks if the $num variable has a value larger than 10. If the result is correct, the message “$num is larger than 10” will appear on the screen. Because there is just one condition to test, PowerShell does nothing if the result is false.

“$num is larger than 10” $num = 11 if ($num -gt 10)

The outcome of pasting the code above into PowerShell is displayed below.

Example of a There is just one If condition.Example of a There is just one If condition.

You may now use the Else statement to set a default “fallback” action instead of having PowerShell do nothing if the test result is false.

If the value of the $num variable is not more than 10, the code in the Else statement will be executed.

If ($num -gt 10) then $num = 9. “$num is greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not greater than 10” if “$num is not

The outcome of running the changed code in PowerShell is displayed below.

There is just one If condition.There is just one If condition.

With PowerShell 7.0, a new ternary operator-based syntax for the If statement was added. This new style is especially useful for single If statements.

This is how the code would appear using the ternary operator, using the same example as before.

11 is the number. “$num is more than 10”: “$num is NOT greater than 10” $num -gt 10?

If the ternary operator is used in the statement syntaxIf the ternary operator is used in the statement syntax

ElseIf allows you to create several If-Else conditions.

When there are many criteria to consider, one or more ElseIf statements are required. Each ElseIf statement has its own test phrase and code to execute.

When the script below is run, it will keep requesting for a fruit name until the user presses CTRL+C or enters the letter “X.”

The If statement will then go through each condition one by one until a match is found. The code within the Else line would be performed if the input did not fit any of the criteria.

While ($fruit -ne “X”) $fruit = Read-Host “Name that fruit” if ($fruit -eq ‘Apple’) ‘I have an Apple’ elseif ($fruit -eq ‘Banana’) ‘I have a Banana’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif ($fruit -eq ‘Orange’) ‘I have an Orange’ elseif

The following is an example of how the script above operates when executed in PowerShell.

There are a lot of If-Else circumstances.There are a lot of If-Else circumstances.

Free Disk Space Status Reporting

Reporting on free disk space is a regular chore for system administrators. The code below is the standard technique of reporting the space information of fixed drives on a Windows computer.

Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object {$_.DriveType -eq 3}

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.DriveType -eq 3 | Get-CimInstance -ClassName CIM LogicalDisk

The information returned by the code above would resemble the one seen in the following snapshot.

Informative report about disk spaceInformative report about disk space

The output above, as you can see, includes the drive letter and free space values, as well as other attributes. While the above result is acceptable, it is not obvious. The way the data is provided makes it impossible to tell if the disk space is critical, warning, or normal.

Improving Code using a PowerShell If Statement

Using the If-Else Statement in PowerShell, a more intuitive output can be achieved by adding conditions to check if the free space is over or below certain thresholds. And these thresholds will define the status of the free disk space.

The following is an example of a script that does the following:

  • Define the threshold at which the % of free space will be marked as crucial using the value of the variable $Critical.
  • Define the threshold at which the % of free space will be classified as warning using the value of the variable $Warning.
  • Take a look at the local machine’s fixed disk information.
  • To detect free space and tag its state, loop over all of the disk information.
    • The disk space status is labeled as normal if the free space % is greater than the value of the $Warning variable.
    • The disk space status is classified as warning if the free space % is greater than the value of the $Critical variable.
    • The disk space status is labeled as critical if the free space % is less than or equal to the value of the $Critical variable.
  • Create the object attributes ‘Drive Letter,”Drive Name,’Total Space (GB),’Free Space (GB),’Free Space (percent),’ and’Status.’
  • Return the completed report.

Copy the code below and save it as Get-DiskSpace.ps1 in your script folder. If you wish to test with various thresholds, don’t forget to alter the values of the $Critical and $Warning variables.

# Define thresholds in percentage $Critical = 20 $Warning = 70 # Get all Fixed Disk information $diskObj = Get-CimInstance -ClassName CIM_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # Initialize an empty array that will hold the final results $finalReport = @() # Iterate each disk information $diskObj.foreach( { # Calculate the free space percentage $percentFree = [int](($_.FreeSpace / $_.Size) * 100) # Determine the “Status” if ($percentFree -gt $Warning) { $Status = ‘Normal’ } elseif ($percentFree -gt $Critical) { $Status = ‘Warning’ } elseif ($percentFree -le $Critical) { $Status = ‘Critical’ } # Compose the properties of the object to add to the report $tempObj = [ordered]@{ ‘Drive Letter’ = $_.DeviceID ‘Drive Name’ = $_.VolumeName ‘Total Space (GB)’ = [int]($_.Size / 1gb) ‘Free Space (GB)’ = [int]($_.FreeSpace / 1gb) ‘Free Space (%)’ = “{0}{1}” -f [int]$percentFree, ‘%’ ‘Status’ = $Status } # Add the object to the final report $finalReport += New-Object psobject -property $tempObj } ) return $finalReport

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $BCCEnabled = $true; $BCCEnable $BCC = “” $BCC = “” $BCC = “” $ $abortFlag = 0; $abortFlag = 0; $abortF if ($SendEmail) =============== Write-Host “[From] is missing” -ForegroundColor Red $abortFlag = 1 if (!$From) Write-Host “[To] is missing” if (!$To) -ForegroundColor Red $abortFlag = 1; $abortFlag = 1; $abortFlag = 1; if ($CCEnabled) =============== $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] is missing” -ForegroundColor Red $abortFlag = 1 if (!$CC) Write-Host “[CC] if ($BCCEnabled) if (!$BCC) Write-Host “[BCC] is missing” -ForegroundColor Red $abortFlag = 1 if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($abortFlag -eq 1) if ($ Write-Host is an acronym for “Write-Host is an acronym for ” “The flag for abort has been triggered. Script to exit.” -ForegroundColor Red break unless otherwise specified -ForegroundColor Green Write-Host “Your email will be sent from this address $From” “And will be emailed to the following people:” Write-Host -Green for the foreground -ForegroundColor Green Write-Host “To: $To” Write-Host “CC: $CC” -ForegroundColor Green if ($CCEnabled -and $CC) Write-Host “BCC: $BCC” -ForegroundColor Green if ($BCCEnabled -and $BCC)

Run the file in PowerShell once you’ve saved it, as shown below. The script’s output when the variable values remain unchanged is shown in the example below.

Example of nested If-ElseExample of nested If-Else

Then, as seen in the excerpt below, change the script and appropriately update all of the variables.

Save the script after making changes to the variables and run it again. It should provide the same result as the example below.

Another Example of nested If-ElseAnother Example of nested If-Else

Change the variables and experiment with various combinations to see how the nested If-Else is impacted. You may better grasp the reasoning by modifying and testing it on your own.

Summary

You learnt about the conditional logic construct — the PowerShell If-Else construct – in this article. Scripters may use the If-Else statement to create conditional logic and steer their scripts’ actions depending on the outcomes of their tests.

You should have learnt how to utilize the If-Else statement when writing decision-driven code from the examples shown in this tutorial. If-Else statements start out basic with a single condition and become more complicated as you go deeper into nested If-Else statements.

What are your thoughts on the If-Else clause? Is this something you believe you’ll be doing more of now that you’ve read this article? What additional applications do you have in mind for the information you’ve gained here?

Additional Reading

.FreeSpace) ‘Free Space (percentage)’ equals “01” -f [int] -f [int] -f [int] ‘Status’ = $Status, $percentFree,’percent ‘ # Include the item in your final report. $finalReport += New-Object psobject -property $tempObj $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalReport $finalRe

After you’ve saved the script, you may test it by typing its name in PowerShell. The following is an example of how this script works.

Command Output for Free Disk Space StatusCommand Output for Free Disk Space Status

The state of each drive is decided by the free disk space %, as you can see from the output, which was the outcome of utilizing numerous criteria using PowerShell If-Else.

If-Else clauses that are multiple and nested

Let’s imagine you have an if-else statement with an else block that contains a condition. If the code within the if block returns false, the else block is triggered when the if-otherwise expression executes.

Another conditional test must be performed within the else section. As a consequence, another If-Else statement is required. This is known as a nested If-Else situation. If the outcome of the action in the outer If-Else is important to the inner If-Else, the nested If-Else statement is widely utilized.

Using If-Else clauses that are multiple and nested statements can be quite confusing. The key point is to remember the scaffold placement and make sure that you indent your code. Indenting your code will help you easily recognize and separate your If-Else statements.

Multiple/Nested If-Else Statements as an Example

The example script below shows how If-Else clauses that are multiple and nested can be dependent on the result of each other. The logic of the code below is as follows.

  • The script will do nothing and quit if $SendEmail is $false.
  • The $From and $To variables must not be empty or null if $SendEmail is $true. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $CCEnabled variable is $true, the $CC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If the $SendEmail variable is $true and the $BCCEnabled variable is $true, the $BCC variable cannot be null or empty. The $abortFlag will be set to 1 if the $abortFlag is not set.
  • If $abortFlag is set to 1, the script will terminate here and not proceed.
  • If $abortFlag is set to 0, the script will run until it reaches the conclusion.

Copy and save the code below as Send-MyMail.ps1. Make no changes to the settings just yet.

$SendEmail = $true; $SendEmail = $true; $SendEmail $To = “” $From = “” $CCEnabled = $true; $CCEnabled = $true; $CCEnabled “” $CC = ” $BCCEnabled = $true; $