You are currently browsing the Gene Laisne's blog blog archives for August, 2009.




By Gene Laisne

Recently I needed to check quickly if twelve systems were up. Rather than writeout each ping command I decided to user PowerShell to do all the heavy lifting. (I’ve been reading up on PowerShell recently)

What I did was write the names of the twelve systems into a text file and issue this command:

foreach ($comp in Get-Content c:\temp\hosts.txt) { ping $comp }

hosts.txt has one system listed per line and as the Get-Content parses the file, it sends each line to the ping command.

Another way would be this:

foreach ($comp in “system1″,”system2″,”system3”) { ping $comp}

On the internet you’ll see this example a lot of the time with something like “foreach ($num in 1,2,3,4,5)” This is nice, but numbers are not strings. If it’s a string, it needs to be in quotes!

If you have a collection of systems that are setup with incrementing DNS names you could do this:

foreach ($hostNumber in 1..10) {ping oit-computer$hostNumber}

This will ping each individual system in turn starting with oit-computer1 and finishing at oit-computer10. (Be sure to use two periods (..) to indicate a span of numbers.)

But, what if you number your systems with leading zeros? Try this trick:

foreach ($hostNumber in 1..10) {$Num = $hostNumber.ToString(“000”); ping OIT-Computer-$Num}

What’s happening here is we have two commands between the { } separated by ‘;’ Don’t forget the ‘;’ otherwise Powershell will error out with “Unexpected token ‘ping’ in expression or statement.” (Each individual element on the line is a token (foreach = token, ( = token, .. = token). First we take our number ($hostNumber) and set it to have leading zeros with the member function ToString(). If you want 4 leading zeros use “0000”.  The result of that change (from 5 to 005 and 10 to 010) goes into the variable $Num. We then use the $Num in the command, directly, without any additional quotes or concatinations. What you get is a series of your systems pinged one at a time.

Now, go a step further if you want, try these commands:

foreach ($hostNumber in 1..255) {$Num = $hostNumber.ToString(“000”); ping 10.100.25.$Num}
foreach ($hostNumber in 1..25) {$Num = $hostNumber.ToString(“000”); nslookup OIT-DSKTOP$Num}
foreach ($user in “gene”,”matt”,”steve”,”jane”) { mkdir \\server\users\$user }
foreach ($comp in “office”,”workstation”,”stevesPC”) { copy c:\temp\file.txt \\$comp\c$\temp }