Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for ping.ps

(view source code of ping.ps as plain text)

  1. param(
  2. 	[parameter( ValueFromRemainingArguments = $true )]
  3. 	[string[]]$hostnames = $Env:ComputerName,
  4. 	[switch]$V,
  5. 	[switch]$h
  6. )
  7.  
  8. if ( $h ) {
  9. 	Write-Host
  10. 	Write-Host "Ping.ps1,  Version 2.00"
  11. 	Write-Host "Ping any number of hosts and return false if any of the pings failed"
  12. 	Write-Host
  13. 	Write-Host "Usage:   " -NoNewline
  14. 	Write-Host "./Ping.ps1  [ hostname  [ hostname  [ ... ] ] ] -V" -ForegroundColor White
  15. 	Write-Host
  16. 	Write-Host "Where:   " -NoNewline
  17. 	Write-Host "hostname    " -ForegroundColor White -NoNewline
  18. 	Write-Host "is a host or list of hosts to be pinged"
  19. 	Write-Host "                     (default: local computer)"
  20. 	Write-Host "         -V          " -ForegroundColor White -NoNewline
  21. 	Write-Host "shows each host's name, IP address and result"
  22. 	Write-Host
  23. 	Write-Host "Note:    Return code is 0 if pings to all hosts were successful,"
  24. 	Write-Host "         1 if any ping failed or if help was requested."
  25. 	Write-Host
  26. 	Write-Host "Written by Rob van der Woude"
  27. 	Write-Host "http://www.robvanderwoude.com"
  28. 	Exit 1
  29. }
  30.  
  31. function Ping-Host {
  32. 	param(
  33. 		[parameter( Mandatory = $true )]
  34. 		[string]$hostname
  35. 	)
  36.  
  37. 	[boolean]$rc = $true
  38.  
  39. 	try {
  40. 		$ping = ( New-Object Net.NetworkInformation.Ping ).SendPingAsync( $hostname )
  41. 		while ( -not ( $ping.IsCompleted ) ) {
  42. 			Start-Sleep -Seconds 1
  43. 		}
  44. 		if ( $V ) {
  45. 			Write-Host $hostname -NoNewline
  46. 			if ( $ping.Status -eq "RanToCompletion" ) { 
  47. 				Write-Host "`t" -NoNewline
  48. 				Write-Host $ping.Result.Address.IPAddressToString -NoNewline
  49. 				Write-Host "`t" -NoNewline
  50. 				Write-Host $ping.Result.Status
  51. 			} else {
  52. 				Write-Host "`tN/A`tFailed"
  53. 			}
  54. 		}
  55. 		if ( $ping.Result.Status -ne "Success" ) {
  56. 			$rc = $false
  57. 		}
  58. 	}
  59. 	catch {
  60. 		if ( $V ) {
  61. 			Write-Host $hostname -NoNewline
  62. 			Write-Host "`tN/A`tFailed"
  63. 			$rc = $false
  64. 		}
  65. 	}
  66. 	return $rc 
  67. }
  68.  
  69. $result = 0
  70. foreach ( $hostname in $hostnames ) {
  71. 	if ( -not ( Ping-Host $hostname ) ) {
  72. 		$result = 1
  73. 	}
  74. }
  75.  
  76. Exit $result
  77.  

page last modified: 2024-02-26; loaded in 0.0237 seconds