PowerShell If Statement


Sometimes you want to divide conditions into some block statements, to do that, we're going to use powerShell if statement. Here condition will be evaluated and return boolean value true or false.

If (condition) {
    statement(s)
}

To get more understanding in this tutorial it's better to know about comparison operator. Let's take a look some examples what you can do with if statement.

if ($a -eq 10) {
    Write-Host "$a is equal with 10."
}

$a = 20
if ($a -gt 10) {
    Write-Host "$a is greater thatn 10."
}

If you have two condition, you can use if else statement.

If (condition)
    statement(s)
else
    statement(s)


$a = 10
if ($a -eq 10) {
    Write-Host "$a is equal with 10."
} else {
    Write-Host "$a is not equal with 10."
}

As the block statement getting more complex, you can use elseif statement.

If (condition)
    statement(s)
elseif (condition)
    statement(s)
else
    statement(s)


$a = 10
if ($a -gt 10) {
    Write-Host "$a is greater than 10."
} elseif ($a -lt 10) {
    Write-Host "$a is less than 10."
} else {
    Write-Host "$a is equal with 10."
}

You can also nested the condition.

$a = 31
if ($a -gt 0) {
    if ($a % 2 -eq 0) {
        Write-Host "$a is positive and even number."
    } else {
        Write-Host "$a is positive and odd number."
    }
} else {
    if ($a % 2 -eq 0) {
        Write-Host "$a is negative and even number."
    } else {
        Write-Host "$a is negative and odd number."
    }
}

Subscribe to receive free email updates:

Related Posts :

  • PowerShell Hash Table Hash table is a dictionary which also data structure that store key/value pairs. Example a hash table taht contain a series of users data… Read More...
  • PowerShell Data Types The following are the most common used data types in powerShell. [string] Fixed-length string of Unicode characters [char] A Uni… Read More...
  • PowerShell Arrays Array is a data structure to store a collection of items, these items can same or different data type. Initalizing and Defining an A… Read More...
  • PowerShell Comparison Operators Comparison operators let is used for comparing values and finding values that match with particular patterns. To use a comparison operato… Read More...
  • PowerShell Variables Variables is the most widely used to stored data in powerShell. Here we can use variables to store data like strings, integers, and obje… Read More...

0 Response to "PowerShell If Statement"

Post a Comment