Quick Loops

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

for ($x=1; $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.


Posted Dec 15 2008, 08:00 AM by ps1
Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.