Coding Ref

How to use If Else in PowerShell

How to use If Else in PowerShell

How to use if statements

To use an if statement in PowerShell, you can use the following syntax:

if (expression) {
    # Code to run if the expression evaluates to true
}

Here, expression is a PowerShell expression that will be evaluated to determine whether the code in the if block should be run. If the expression evaluates to true, the code in the if block will be executed. Otherwise, it will be skipped.

For example, you might use an if statement to check whether a variable has a certain value, and run some code only if it does:

$myVariable = "Hello, world!"

if ($myVariable -eq "Hello, world!") {
    Write-Output "The variable has the expected value."
}

In this case, the if statement would check whether the value of $myVariable is equal to the string "Hello, world!", using the -eq operator.

If the values are equal, the code in the if block would be executed, and the message "The variable has the expected value." would be output to the console.

How to use if else statements

You can also use an else block to specify code that should be run if the expression in the if statement evaluates to false:

$myVariable = "Hello, world!"

if ($myVariable -eq "Hello, world!") {
    Write-Output "The variable has the expected value."
} else {
    Write-Output "The variable does not have the expected value."
}

In this case, if the value of $myVariable is not equal to "Hello, world!", the code in the else block would be executed, and the message "The variable does not have the expected value." would be output to the console.

How to use multiple if else statements

You can also use multiple elseif blocks to check for multiple conditions in a single if statement:

$myVariable = "Hello, world!"

if ($myVariable -eq "Hello, world!") {
    Write-Output "The variable has the expected value."
} elseif ($myVariable -eq "Goodbye, world!") {
    Write-Output "The variable has a different, but still acceptable, value."
} else {
    Write-Output "The variable does not have an acceptable value."
}

In this case, if the value of $myVariable is equal to "Hello, world!", the code in the first if block would be executed.

If it's equal to "Goodbye, world!", the code in the elseif block would be executed. Otherwise, the code in the else block would be executed.

You'll also like

Related tutorials curated for you

    The difference between add-content and set-content

    PowerShell do-while loop

    How to declare global variables in PowerShell

    How to ping in PowerShell

    How to run a .bat file in PowerShell

    How to copy and paste into PowerShell

    How to create an alias in PowerShell

    How to use String Contains in PowerShell

    How to write multiple-line comments in PowerShell

    How to rename a file in PowerShell

    Dictionaries in PowerShell

    What is a Scriptblock in PowerShell?