Wednesday 29 June 2016

An Introduction to PowerShell – If/Then

The simplest form of decision making in PowerShell is the if/then mechanism.

The code that runs if your comparison clause is YES/TRUE or NO/FALSE must be surrounded within curly braces, it is best practice to put these curly braces on lines by themselves so that you can match them up when you are writing more complicated scripts.
If condition is met then

{

Do This

}

Else

{

Do This

}

Example:
If (20 –gt 15)

{

Write-Host "20 is Greater than 15"

}

 

PS-7

Here the –gt is the PowerShell switch for "greater than".

 

Another Example using Nesting
If (20 –gt 25)

{

Write-Host "20 is Greater than 25"

}

elseif (25 –gt 20)

{

Write-Host "25 is Greater than 20"

}

PS-8

You can include n number of these elseif blocks in your script, there is no maximum limit for how many times it occurs in script.
If (10 –gt 11)

{

Write-Host "10 is Greater than 11"

}

elseif (11 –lt 10)

{

Write-Host "11 is Less than 10"

}

elseif (20 –gt 40)

{

Write-Host "20 is Greater than 40"

}

else

{

Write-Host "None of above conditions are true"

}

PS-9

I will come up with more stuffs in my upcoming posts.

Till then keep practicing and stay tuned for more details.

No comments:

Post a Comment