Thursday, July 30, 2009

A useful Test-Host Function

BS on Posh (tshell) have created a Test-Host function that is very useful. I have written some of these functions myself, but this beats the ones I have made, so I’ll switch :)

Test-Host supports normal ping but as ping is not always sufficient - may be blocked or you may have to wait for a service to be ready (who said RDP?) - TCP port is also supported. Finally, Test-Host accepts the server name as argument or from the pipeline (using V2 parameter binding) and it even allows you to specify a property, in case the server name is part of the object.

Test-Host sends the server argument down the pipeline, if that server is reachable. In this way, Test-Host acts more like a filter than a classic Test-Cmdlet. Maybe it could have been called Where-HostReachable or similar?

Another comment I have, is that the server argument should have been called ComputerName (to follow other Cmdlets). To make the function more flexible, alternative names like server and name could have been specified with [Alias()]. A quick fix here is to add ComputerName and Name as aliases: [Alias("ComputerName","Name")] Place the text before the $server parameter.

I also found a bug in the code. You have to remove the [string] before the $server to be able to use $property. If server is forced into a string, the properties are lost and thus cannot be selected.

Some examples of it use -

Ping test (not reachable)
PS> test-host www.dr.dk

TCP port 80 test (reachable)
PS> test-host www.dr.dk -tcp 80
www.dr.dk

Ping test (reachable)
PS> test-host www.jp.dk
www.jp.dk

Ping test (not reachable)
PS> test-host 1.2.3.4

TCP port 80 test (reachable)
PS> test-host 1.2.3.4 -tcp 80

Pipe names
PS> "www.dr.dk","www.jp.dk" | test-host -tcp 80 | foreach {"Web server runs on $_"}
Web server runs on www.dr.dk
Web server runs on www.jp.dk

Pipe names, one not reachable
PS> "www.dr.dk","www.jp.dk","nosuchserver" | test-host -tcp 80 | foreach {"Web server runs on $_"}
Web server runs on www.dr.dk
Web server runs on www.jp.dk

Build objects array with two servers
PS> $objs=@()
PS> $obj="" | select Server,Role; $obj.server="www.dr.dk"; $obj.role="webserver"; $objs+=$obj
PS> $obj="" | select Server,Role; $obj.server="nosuchserver"; $obj.role="mailserver"; $objs+=$obj
PS> $objs

Server Role
------ ----
www.dr.dk webserver
nosuchserver mailserver

Test, selecting the Server property as the name
PS> $objs | test-host -tcp 80 -property Server | foreach {"Server $_ is running"}
Server @{Server=www.dr.dk; Role=webserver} is running

Test, constructing a ComputerName property to show the alias parameter binding
PS> $objs | select @{n="Computername";e={$_.server}} | test-host -tcp 80 -property ComputerName| foreach {"Server $_ is running"}
Server @{Computername=www.dr.dk} is running







No comments: