,

Powershell: if Statement basics

1–2 minutes
4 comments on 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.

4 responses

  1. Tech Support Avatar
    Tech Support

    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. Gary Avatar

    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?

  3. Lars Panzerbjrn Avatar
    Lars Panzerbjrn

    A bit late, I know, but there is a typo here, in the first line: “The Iif Statement”.

  4. raja Avatar

    i want example of using blob container only access one container remaining containers delete..
    can u share me the example

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.