Learn

Conditional statements in Powershell are the same, conceptually, as conditional statements in any programming language. They are sections of code that execute based on provided conditions.

You can think of conditional statements as a fork in the road. When you get to it, a decision about which direction to go needs to be made. Virtually any script you write will perform various activities, but your script will inevitably need to make logical determinations.

Let’s start with the if statement:

$myVar = 2 if ($myVar -eq 2) { Write-Host "A True Statement" } Write-Host "After the if statement"

The above example will output A True Statement! since $myVar does equal 2. The code will finish with the output, After the if statement.

if statements consist of two parts:

  • The conditional statement inside the parentheses, $myVar -eq 2,
  • The body inside the curly brackets is the code to run if the condition is true, A True Statement!

Alternatively, when $myVar is anything but 2, the code inside the if statement body will not run, and only After the if statement will be output.

Instructions

1.

The script if_example.ps1 defines a variable $var.

Write an if statement below the variable definition to test if $var equals 5. Be sure to include curly braces for the body, but leave them empty.

2.

Use Write-Host to output “It’s a match” if the conditions are met.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?