Thursday, July 3, 2008

Simple PING test: VBScript vs PowerShell

As a preparation for my TechEd Asia 2008 session on Windows PowerShell, I've been trying to convert a few of my administrative scripts to demonstrate how easy tasks can be done using PowerShell. Here's one I just did: simple PING test. Here's a sample VBScript code that checks whether a PING test is successful or not. I call the VBScript and pass it a parameter which is the hostname or IP address of the computer I want to ping

strComputer=Wscript.Arguments.Item(0) 'parameter passed = hostname

wmiQuery = "Select * From Win32_PingStatus Where Address = '" & strComputer & "'"

Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objPing = objWMIService.ExecQuery(wmiQuery
For Each objStatus In
If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0
Reachable = False
'if computer is unreacable, return false
Reachable = True
'if computer is reachable, return true
End If

Wscript.Echo Reachable

Here's the equivalent script using PowerShell

$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.Send($hostname)


You can see how much easier it is to accomplish a simple task in PowerShell. It makes the life of an administrator much better, especially if you have to write scripts that automate repetitive tasks. I'll post more samples of the VBScript codes you've probably seen in this blog converted to PowerShell

Tuesday, July 1, 2008

So your PowerShell script won't run?

In case you're wondering why on earth your PowerShell scripts don't run, its because scripting in Windows PowerShell is not enabled by default. Imagine your custom .NET assemblies being blocked until such time you register them on your global assembly cache (GAC). This is to make sure you don't run just about any script on your system. This is normally referred to as the restricted execution policy. You'll probably encounter something like this if it's the first time you'll run a PowerShell script

You can find out more about execution policy in Windows PowerShell by typing Get-Help Set-ExecutionPolicy on your PowerShell command window. You should also make sure that you have permissions to run scripts on your machine. Check either your local or your domain security policy to be sure. Plus, unlike VBScript where you can just double-click and run, PowerShell scripts don't behave that way. You need to call PowerShell before running the script. This is to make sure you don't accidentally run the script by just double-clicking. It does make sense especially if your machine get's exploited by a virus or a worm.