Boolean

Boolean values are just statements that return true or false. For example, does 1 + 1 equal 2? This would be true. How would this look in code well here is an example.

C:\> $result = 1+1
# The answer to 1+1 which is 2 will be stored in the variable $result
# This is where we will use an if statement.
If($result -eq 2){
     Write-Output "My value is equal to $result"
}
My value is equal to 2
C:\>

Notice in the above if statement since $result was -eq (equal) to 2 the text “My value is equal to 2” was printed to the screen. Also notice instead of typing the number 2 we used the variable $result.

Now lets say the value wasn’t equal to 2 then what? Well with if statements you can have an else. So If the result is true do this ELSE do that. Below is an example.

C:\> $result = 1+2
# The answer to 1+2 which is 3 will be stored in the variable $result
# This is where we will use an if statement.
If($result -eq 2){
     Write-Output "My value is equal to $result"
}else{
     Write-Output "$result is not equal to 2"
}
3 is not equal to 2
C:\>

Notice we updated the math to be 1+2 so our result is 3 and added the else statement. Since $result -eq 2 returns false the code jumps to the else statement and runs that code. Now you could do the reverse and say if it is NOT true then do this else that by using the ! character.

C:\> $result = 1+1
# The answer to 1+1 which is 2 will be stored in the variable $result
# This if statement is now reverse now
# If the comparison is NOT true the run the first block ELESE rune the second
If(!($result -eq 2)){
     Write-Output "$result is not equal to 2" 
}else{
     Write-Output "My value is equal to $result"   
}
My value is equal to 2
C:\>

I know using the (!($result -eq 2) can be super confusing but if you see it in the wild you’ll know now. If you see it then the first block is for FALSE and the Else if for TRUE.

Here are most of the operators I can think of:

OperatorDescription
-eqequals
-neNot equal to
-gtGreater Than
-geGreater than or equal to
-ltLess than
-leLess than or equal to
-likeUsed for matching strings (“Ma*” -like “Matt”)
-NotlikeString not like another
-matchUsed with regex
-containsSee if word is in an collection (Array)
-notcontainsSee if a word is not in a collection (Array)

Leave a Reply

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

Close Bitnami banner
Bitnami