Thursday, April 16, 2009

First Powershell Script

Windows Powershell is another attempt from Redmond to provide powerful windows scripting language to IT professionals. But this time, I would say that it is a successful attempt by Microsoft.

Windows Powershell is often being compared with Unix Bash Shell. But it actually does more than what you may expect. Unlike its Unix counterpart, the PowerShell pipeline is an object pipeline; that is, the data passed between cmdlets are fully typed objects, rather than byte streams. A cmdlet, pronounced "command-let" is same as what you call "shell script" in Unix. So don’t get confused with cmdlets

I have read more reviews on Powershell and excited to see Powershell in action. I'm posting all my learning as I learn so it could be useful to everyone.

Click here to download Windows PowerShell 2.0 Community Technology Preview (CTP)

So Here is your first simple “Hello World” script:


PS C:\Documents and Settings\jagadish.g> Write-Host "Hello World"
Hello World
PS C:\Documents and Settings\jagadish.g>

Write-Host cmdlet is similar to echo in Unix. You can specify separator, background color, foreground color and more.


PS C:\Documents and Settings\jagadish.g> Write-Host (10,10,12)
10 10 12
PS C:\Documents and Settings\jagadish.g> Write-Host (10,10,12) -Separator "+"
10+10+12
PS C:\Documents and Settings\jagadish.g> Write-Host (10,10,12) -Separator "+" -ForegroundColor Green -BackgroundColor Black
10+10+12
PS C:\Documents and Settings\jagadish.g>


Now we will go through some simple cmdlets.

Get-Process
    Gets the processes that are running on the local computer or a remote computer


PS C:\Documents and Settings\jagadish.g> Get-Process | Select-Object -First 3

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
32 2 780 2708 28 0.05 1296 acrotray
107 5 1168 3524 32 0.03 2712 alg
203 7 3584 6648 43 0.36 3724 btdna

PS C:\Documents and Settings\jagadish.g>

Get-Service
    Gets the services on a local or remote computer


PS C:\Documents and Settings\jagadish.g> Get-Service | Select-Object -First 3

Status Name DisplayName
------ ---- -----------
Stopped Alerter Alerter
Running ALG Application Layer Gateway Service
Stopped AppMgmt Application Management

PS C:\Documents and Settings\jagadish.g>


If you have any questions on Powershell, please post them in the below comments section