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 ...

Get Mastering Windows PowerShell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.