PowerShell/scripts/ping-hosts.ps1

52 lines
1.7 KiB
PowerShell
Raw Normal View History

2023-11-08 13:44:17 +01:00
<#
.SYNOPSIS
Pings the local hosts
.DESCRIPTION
2023-11-08 13:55:50 +01:00
This PowerShell script pings well-known hostnames in the local network and lists which one up.
2023-11-08 13:44:17 +01:00
.EXAMPLE
PS> ./check-hosts.ps1
2023-11-08 13:55:50 +01:00
Up are: Hippo Jenkins01 Jenkins02 Rocket Vega
2023-11-08 13:44:17 +01:00
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
2023-11-08 13:55:50 +01:00
[string]$hosts = "Amnesiac,Boston,Castor,Cisco,Fedora,Fireball,Firewall,fritz.box,Gateway,Hippo,Io,Jarvis,Jenkins01,Jenkins02,Laptop,Jupiter,Mars,Mercury,Miami,Mobile,NY,Paris,Pluto,Proxy,R2D2,Rocket,Router,Server,SmartPhone,SmartWatch,Sunnyboy,Tablet,Ubuntu,Vega,Venus,Zeus" # sorted alphabetically
[int]$timeout = 600 # milliseconds
2023-11-08 13:44:17 +01:00
$hostsArray = $hosts.Split(",")
$count = $hostsArray.Count
Write-Progress "Sending pings to $count local hosts..."
$queue = [System.Collections.Queue]::new()
foreach($hostname in $hostsArray) {
$ping = [System.Net.Networkinformation.Ping]::new()
2023-11-08 13:55:50 +01:00
$object = @{ Host = $hostname; Ping = $ping; Async = $ping.SendPingAsync($hostname, $timeout) }
2023-11-08 13:44:17 +01:00
$queue.Enqueue($object)
}
[string]$result = ""
while ($queue.Count -gt 0) {
$object = $queue.Dequeue()
try {
2023-11-08 13:55:50 +01:00
if ($object.Async.Wait($timeout) -eq $true) {
2023-11-08 13:44:17 +01:00
if ($object.Async.Result.Status -ne "TimedOut") {
$result += "$($object.Host) "
}
continue
}
} catch {
if ($object.Async.IsCompleted -eq $true) {
continue
}
}
$queue.Enqueue($object)
}
Write-Progress -completed "Done."
Write-Host "✅ Up are: $result"
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}