Written by 9:10 pm Microsoft, PowerShell • 4 Comments

Powershell: if Statement basics

Powershell Header

The if-statement is pretty important if you are creating PowerShell scripts. So I created this post to get some basic information about how to use if-else statements with PowerShell.

PowerShell if-else statement basics

Like many other languages, PowerShell has statements for conditionally executing code in your scripts. One of those statements is the If statement.

First, the syntax with a simple if:

if (condition) {do}

You can also use elseif and else:

if (condition) {do}
elseif (condition) {do}
else {do}

A simple if could look like this:

if ($varibale -eq "1") {
Write-Host "Yes variable is 1"
}

Comparison Operators:

  • Equal to: -eq
  • Less than: -lt
  • Greater than: -gt
  • Greater than or Equal to: -ge
  • Less than or equal to: -le
  • Not equal to: -ne

You can also check case-sensitive by adding a “c” to the operator. “-eq” would be “-ceq

Logical Operators:

  • Not -not
  • Not !
  • And -and
  • Or -or

So you can simply add multiple conditions:

if ($varibale -eq "1" -or $varibale -eq "2") {
Write-Host "Varibale is 1 or 2"
}

Conclusion

I hope this provides you with a simple and short overview of how to use if-else statements with PowerShell. If you have any questions feel free to leave a comment. If you want to learn more, check out Microsoft Docs.

Tags: , , , , , , , , , , Last modified: December 22, 2020
Close Search Window
Close