Cool Trick if You Use Sequential Server Names

The range operator in PowerShell can be the key to some really cool tricks.

Don Jones

June 29, 2011

1 Min Read
ITPro Today logo in a gray background | ITPro Today

I recently did a tour of six West coast Microsoft offices, doing a little three-hour talk on PowerShell. At the end, as is customary, we raffled off some stuff. One of the Microsoft IT Pro Evangelists accompanying me had a unique raffle methodology: He collected everyone's evaluation forms andthrew them at me. I was supposed to snatch winners out of the air. Thanks, Harold, and I'll bill you for the therapy.

My solution - after being accosted by a ream of flying paper - was to run this in PowerShell:

1..100 | Get-Random


I replaced "100" with however many evals we actually had, and the .. range operator generated that many numbers. Get-Random then chose... well, a random one of those. I made someone else count down that many evals to find the winner.

It come me thinking about other uses of the range operator. For example, I name my DCs sequentially: DC1, DC2, and so forth. Invoking a command on them becomes easy:

Invoke-Command -script { Get-Process } -computername ( ForEach ($n in 1..10) { Write-Output "DC$n" })


I know, I hate ForEach - but this is a case where it's the only real solution, so I'm knuckling down and using it. 

Do you know any cool tricks for the range operator?

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like