In PowerShell, the if keyword is used to create conditional statements that execute different blocks of code based on the evaluation of a specified condition. The else keyword is used to specify an alternative block of code to be executed if the condition specified with the if keyword evaluates to false.
The probably most used function in PowerShell is the IF and Else statement. For example: If something contains this, delete an item or do nothing. In this tutorial, I will show you the basics of an If and Else statement.
This example is the most simple implementation, with the operators Match and Equals.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#This is a variable: Which contains the text Hello $YourComputerFix = "Hello" #Now we check if the Variable matches Hello IF($YourComputerFix -match "Hello"){ Write-host "YES It Match hello" } Else { Write-host "NO It does not match Hello" } Output: YES It Match hello #Now we check if the Variable equals HelloW IF($YourComputerFix -eq "HelloW"){ Write-host "YES It Match hello" } Else { Write-host "NO It does not match Hello" } Output: NO It does not match Hello |
A more complex IF Else statement is with more than one IF. Then the ElseIf could be used.
So If this condition is not true, go on with the test in ElseIf, if both of the If’s are False. Use the last resort the Else Statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#This is a variable: Which contains the number 14 $YourComputerFix = 14 if($YourComputerFix -eq 10){ write-host("Value is 10") } elseif($YourComputerFix -gt 20){ write-host("Value is greater than 20") } elseif($YourComputerFix -lt 30){ write-host("Value is lower than 30") } else { write-host("This is else statement") } Output: Value is lower than 30 |