Looping and branching
Comparing values
Test if something is equal
$a = 10
$b = 10
$a -eq $b
Test if something is not equal
$a = 10
$b = 11
$a -eq $b
-not ($a -eq $b)
$a -ne $b
Value is lesser or greater than
$a = 10
$b = 11
$a -lt $b
$b -gt $a
Value is lesser or equal or greater or equal than
10 -le 10
9 -le 10
11 -ge 10
10 -ge 10
String comparisson
$str1 = "Hello"
$str2 = "hello"
$str1 -eq $str2
$str1 -ceq $str2
$str1 -ieq $str2
Check if string (sub) matches regex
$greeting = "Hello Bob, is everything ok with you?"
$name = "Bob"
$greeting -match $name
Show matches
$matches
References: Comparisson Operators
Boolean type
Boolean type
$true
$false
$true -ne $false
(10 -eq 11) -eq $false
0 -eq $false # true
1 -eq $true # true
2 -eq $true # false
$false -eq 0 # true
$true -eq 1 # true
$true -eq 2 # true
[int]$true
[boolean]2
[boolean]2 -eq [boolean]$true #true
"" -eq $false #false
$false -eq "" #true
[boolean]""
[string]$false
Null type
$notexisting
$notexisting -eq $false
$notexisting -eq $true
$notexisting -eq $null
And, Or
$a = 10
($a -gt 5) -and ($a -lt 100)
($a -lt 20) -or ($a -gt 100)
References: Logical Operators
Branching
If, then else
[int]$a = 3
[int]$b = 5
if ($a -eq $b) {
write-host "They are the same"
} else {
write-host "They are not the same"
}
If, Else If or else
[int]$a = 3
if ($a -eq 3) {
write-host "A is three"
} elseif ($a -eq 2) {
write-host "A is two"
} else {
write-host "I don't know how to spell $a"
}
Switch case
[int]$a = 3
switch($a) {
1 {
write-host "A is one"
}
2 {
write-host "A is two"
}
3 {
write-host "A is three"
}
default {
write-host "I don't know $a"
}
}
Loops
While Loop
$i = 0
while ($i -lt 10) {
write-host "Step $i"
$i++
}
For Loop
for ($i = 0;$i -lt 10;$i++) {
write-host "Redoing $i"
}