lørdag den 21. januar 2012

Hello Powershell

For a long time I have thought about writing a hello world  on Powershell.. I have done a lot of scripting in my career and Powershell is a great step in the right direction.

So lets get it fired up.
But.. it just looks like a command prompt.. whats so special about that.. Well wait and see. First of all lets do the general Hello world.  In the prompt write:

Write-host "Hello world"

And it returns Hello world as you might imagine.. WOW?? not yet.. Lets try another little thing. Try to write get-pr and press the Tab key. It now fills out the rest and writes Get-Process. Thats great, it has autocompletion .. Press enter, and see the running processes.. Impressed??

Now for something even better. The pipelining. (|) when you write a command it returns an object. This object can be further processed by another command after the pipecharacter through the variable $_. So when you write Get-Process you'll receive a collection of processes, and if you see at the top of the list, the propertynames are shown.
This'll lead us to the first wow.. Try to write :

Get_Process |  Where-Object {$_.ProcessName -like "wi*" }

Now you should see only the processes where the processname starts with wi. So to make a final Hello world in this blog. Try to write


Get-Process | Where-Object {$_.ProcessName -like "wi*" } | ForEach-Object {Write-Host "Hello" $_.ProcessName }

Now you should have a hello for the processes.