Powershell Header

Powershell: if Statement basics

The if Statement is pretty important if you are creating PowerShell scripts. So I created this post to get some basic information here.

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 Eqaul 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"