Powershell: if Statement basics

Powershell Header

The Iif Statement is a 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"
}

Related Posts:

2 thoughts on “Powershell: if Statement basics

  1. Dear Professional,
    Neew your assist to run following IF script in powershell

    $Dgroup = read-Host type Dl name
    $User = read-host type user name

    if (Get-Distributiongroup -Identity $Dgroup -ManagedBy $User )

    {Write-Host ‘$user is correct owner’}

    Else
    {Write-Host ‘type correct user name’}

  2. Sweet and simple, I like it, thanks.

    However, I came across your blog through searching for a solution to a problem I’m having. Can you shed some light on to why the uncommented bottom if -or statement works while the commented statement does not?

    # if ($TempEnvironment -ne “dev” -or $TempEnvironment -ne “acpt” -or $TempEnvironment -ne “prod”) { …code }

    The above statement steps into the code regardless.
    The below statement works and steps over on a true condition.

    if (!($TempEnvironment -like “dev” -or $TempEnvironment -like “acpt” -or $TempEnvironment -like “prod”)) { …code }

    Would anyone know why?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>