Command-line shortcut for repetitive operations

Thu, Jul 28, 2005 One-minute read

There are times when you might want to do the same thing many times at the command line.  You normally would use a counted for loop:

MSH:19 C:\temp\monad > for($x = 0; $x -lt 5; $x++) { do-something }

But here’s a neat little trick to save some typing, if you don’t care which iteration of the loop you’re in:

MSH:19 C:\temp\monad > 1..5 | foreach { do-something }

This is a bloated and slow way to do a for loop, though, so don’t use it in scripts.

The 1..5 expression creates an array of 5 elements, using the numbers 1 through 5.  Then, we pipe it to foreach-object – which then performs “do-something” for each element in the array.

For more neat things you can do with arrays, type

get-help about_Array

at your prompt.

[Edit: Monad has now been renamed to Windows PowerShell. This script or discussion may require slight adjustments before it applies directly to newer builds.]