Wednesday, May 19, 2010

PowerShell

Ok, so I know I'm not a huge proponent of Micro$oft products, but I'd have to say this one is pretty good. I just started learning powershell about a month ago for my job and I already have some pretty sweet scripts written that save me tons of time.

What is it exactly? It's the latest scripting environment from Microsoft that includes a shell (basically a command console like a DOS window on steroids) and a new scripting / command language. It's M$'s way of catching up with the UNIX world and shell scripting.

The neatest feature of the scripting language I think is the fact that everything is an object and that you can pipe objects to other object's methods to produce results. For instance, the following script shows how to write your own ping function.

$ping = new-object System.Net.NetworkInformation.Ping
$result = [System.Net.Dns]::GetHostByName("$strComputer")
$result.AddressList (PIPE) ForEach-Object {

$Reply = $ping.send($_.IPAddressToString)
if($Reply.status -eq "Success")
{
$Reply (PIPE) Select-Object Status,Address,RoundTripTime (PIPE) Format-Table
}else{
write-host "Host $strComputer ($_) ping FAILED with response:" $Reply.status
}
}


Produces the following:

yahoo.com

Status Address RoundtripTime
------ ------- -------------
Success 72.30.2.43 84

Status Address RoundtripTime
------ ------- -------------
Success 98.137.149.56 88

Status Address RoundtripTime
------ ------- -------------
Success 209.191.122.70 40

Status Address RoundtripTime
------ ------- -------------
Success 67.195.160.76 32

Status Address RoundtripTime
------ ------- -------------
Success 69.147.125.65 33


As you can see from this, you can also create and use objects that belong to the .Net framework. If you're any kind of developer, you can see the power in this. You can even go as far as using the Windows.Forms objects to create a GUI for your scripts and interact with the user with text boxes, lists, labels, buttons, etc. Crazy stuff!

For some reason my code above won't show the pipe character, so in it's place, I'll use "(PIPE)".