Quick Loops

by Dec 15, 2008

Normally, creating a simple loop in PowerShell can be a bit awkward:

for ($x=$x -le 10; $x++) { $x }

A much more readable way works like this (and uses an array internally):

foreach ($x in 1..10) { $x }

Loops are fun as you can easily create your personal ASCII character reference table simply by casting the number to a character:

foreach($x in 32..255) { "$x = $( [char]$x )" }

Or create enumerated lists:

foreach ($x in 1..20) { 'Server{0:00}' -f $x }

Use the -f operator to insert formatted data into the template string. {0:00} is a placeholder in your template, which basically tells PowerShell to insert the number as a two-digit number, appending leading zeroes to it.