Wednesday 25 March 2009

Get-PingStatus.ps1


  1. <#  
  2. .SYNOPSIS  
  3.     Demonstrates use of the Win32_PingStatus WMI class    
  4. .DESCRIPTION  
  5.     This script is a community content MSDN sample,using PowerShell  
  6. .NOTES  
  7.     File Name  : Get-PingStatus 
  8.     Author     : Thomas Lee - tfl@psp.co.uk  
  9.     Requires   : PowerShell V2 
  10. .LINK  
  11.     Sample posted to:  
  12.         http://pshscripts.blogspot.com/2009/03/get-pingstatusps1.html    
  13.       
  14. .PARAMETER Comp 
  15.     The computer you want to ping - should be resolvable by DNS 
  16. .EXAMPLE  
  17.     PSH [C:\foo]:  .\Get-PingStaus.ps1 blogger.com 
  18.     Computer to ping:       blogger.com 
  19.     Computer responded in:  127ms 
  20. .EXAMPLE 
  21.     PSH [C:\foo]: "blogger.com", "Localhost" | . 'C:\foo\to post\get-pingstatus.PS1' 
  22.     Computer to ping:       blogger.com 
  23.     Computer responded in:  127ms 
  24.     Computer to ping:       Localhost 
  25.     Computer responded in:  0ms 
  26. .EXAMPLE 
  27.     PSH [C:\foo]:  .\Get-PingStaus.ps1  
  28.     Computer to ping:       localhost 
  29.     Computer responded in:  0ms 
  30. #>  
  31.  
  32. [Cmdletbinding()] 
  33. param (  
  34. [Parameter(Position=0,mandatory=$false,ValueFromPipeline=$true)] 
  35. [string] $comp = "localhost"
  36.  
  37. ###  
  38. # Start of Script  
  39. ###  
  40.  
  41. Process { 
  42. # Display intput 
  43. "Computer to ping:       $comp" 
  44.  
  45. # Now ping the system 
  46. $ping = get-wmiobject -Query "select * from win32_pingstatus where Address='$comp'" 
  47.  
  48. # Display Results 
  49. if ($ping.statuscode -eq 0) { 
  50. "Computer responded in:  {0}ms" -f $ping.responsetime 
  51. else
  52. "Computer did not respond" 

2 comments:

John J. Kavanagh said...

Just curious why the WMI method versus System.Net.NetworkInformation.ping . When I first got into Powershell this question came up and specifically with the ping routine. Using the .Net method seems to be faster but that could be based on several factors (such as sloppy coding on my part).

Thomas Lee said...

There's no reason why one vs the other. The script was created as a sample for MSDN, and was published here!

I suppose it depends on your needs. If you are doing lots of WMI related stuff, then use the WMI interface. If you are writing managed code, then the .NET implementation is used.

I'll have to take a look at the .ping .NET class, recode this script using that interface.