Skip to content

Instantly share code, notes, and snippets.

@dragon788
Created April 12, 2017 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dragon788/7122dceabc848ad2c5473c9344428bec to your computer and use it in GitHub Desktop.
Save dragon788/7122dceabc848ad2c5473c9344428bec to your computer and use it in GitHub Desktop.
Robust PowerShell ping with error checking :P
function Get-Ping ($url) {
$timeout = 500
$ping = new-object system.net.networkinformation.ping
try {
# The @() ensures the return if a single string is still an array
$urlArray = @($url.split(' ') | where { $_ -ne "-" })
#"urlArray = $urlArray"
$url = $urlArray[0]
#$url
$ip = $urlArray[1]
#$ip
} catch {
# We don't care if no IP was found
}
try {
$response = $ping.Send($url,$timeout) | select address,status
if ($ip) {
if ($response.Address -ne $ip) {
write-error "The returned address $($response.Address) didn't match the expected IP $ip"
}
}
return "$url $($response.Status)"
} catch {
write-host "No reply from host, address $url appears to be available"
}
}
$error.clear()
$errorCount = $($Error.Count)
$result = foreach ($url in $urls) { Get-Ping $url }
#$result = foreach ($url in $urls) { ping -a -n 1 $url } # Useful if above gives "out of resources" aka sockets?
$result | ft -AutoSize
$newErrorCount = $($Error.Count)
if ($errorCount -ne $newErrorCount) {
Write-Host "Some errors occurred, not all URLs ready"
foreach ($error in $($newErrorCount - $errorCount)) {
Write-Host "Most recent error was: $($Error[$error])"
}
}
# This was developed for an internal tool to spit out DNS requests in a format
# the network team could pretty much copy and paste into their tools
Get-Ping "something.mydomain.com - 192.168.1.100 - SOMEHOSTNAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment