Increment and decrement

The ++ and -- operators are used to increment and decrement numeric values. The increment and decrement operators are split into pre-increment and post-increment versions.

The post-increment operators are frequently seen in for loops. The value for $i is used, and then incremented by one after use. In the case of the for loop, this happens after all the statements inside the loop block have executed:

for ($i = 0; $i -le 15; $i++) { 
    Write-Host $i -ForegroundColor $i
}

The post-decrement reduces the value by one after use:

for ($i = 15; $i -ge 0; $i--) { 
    Write-Host $i -ForegroundColor $i
}

Post-increment and post-decrement operators are often seen when iterating through an array:

$array = 1..15 
$i = 0 
while ($i -lt $array.Count) { 
    # $i will increment after this statement has completed. 
    Write-Host $array[$i++] -ForegroundColor $i 
} 

Pre-increment and pre-decrement are rarely seen. Instead of incrementing or decrementing a value after use, the change happens before the value is used, for example:

$array = 1..5 
$i = 0 
do { 
    # $i is incremented before use, 2 will be the first printed. 
    Write-Host $array[++$i]
} while ($i -lt $array.Count -1)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.195.225