Powershell - Pre and post increment/decrement

To support me, you can subscribe to the channel, share and like the videos, disable your ad blocker or make a donation. Thank you!

Hello,

Today I propose to play with increments/decrement in PowerShell, known by the ++ or — syntax and more specifically with pre- and post-increment/decrement

# Post increment
$i = 2
$i++ # 3
$i
$i++ # 4
$i
# Post decrement
$i = 6
$i-- # 5
$i
$i-- # 4
$i
# Pre increment
$i = 2
++$i # 3
$i
--$i # 2
$i
# Apart from the difference in the location of the increment/decrement operator, there is no visible change.
# Let's check with another code
# The increment is performed after the declaration (analysis of the condition)
$i = 1
Do {
$i
} While ( $i++ -le 4 )
# The increment is performed before the declaration (the analysis of the condition)
$i = 1
Do {
$i
} While ( ++$i -le 4 )
# Another demonstration
$array = 1..10
$i, $a = 0
while ($i -lt $array.Count) {
# The increment is performed after the declaration.
Write-Host $array[$i++] -ForegroundColor yellow
# The increment is performed before the declaration
Write-Host $array[++$a] -ForegroundColor green
"i is $i, a is $a
}
# $i is 10 displays a result since it has the value 9 in the declaration and is incremented after the declaration
# $a is 10 (incremented before the declaration) does not display any results as there is no index 10 in $array

Related links