PowerShell/scripts/ping-local-hosts.ps1

51 lines
1.8 KiB
PowerShell
Raw Normal View History

2023-11-08 13:44:17 +01:00
<#
.SYNOPSIS
2023-11-09 07:25:36 +01:00
Pings local hosts
2023-11-08 13:44:17 +01:00
.DESCRIPTION
This PowerShell script pings the computers in the local network and lists which one are up.
2023-11-08 13:44:17 +01:00
.EXAMPLE
PS> ./ping-local-hosts.ps1
Up: 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 {
2024-01-03 11:59:38 +01:00
Write-Progress "Sending pings to the local hosts..."
2023-11-17 18:57:50 +01:00
[string]$hosts = "Amnesiac,ArchLinux,Berlin,Boston,Brother,Canon,Castor,Cisco,EchoDot,Epson,Fedora,Fireball,Firewall,fritz.box,GasSensor,Gateway,Hippo,HomeManager,Io,iPhone,Jarvis,Jenkins01,Jenkins02,LA,Laptop,Jupiter,Mars,Mercury,Miami,Mobile,NY,OctoPi,Paris,Pixel-6a,Pluto,Printer,Proxy,R2D2,Raspberry,Rocket,Rome,Router,Server,Shelly1,SmartPhone,SmartWatch,Soundbar,Sunnyboy,Surface,Switch,Tablet,Tolino,TV,Ubuntu,Vega,Venus,XRX,Zeus" # sorted alphabetically
2023-11-08 13:44:17 +01:00
$hostsArray = $hosts.Split(",")
$count = $hostsArray.Count
2024-01-03 11:59:38 +01:00
[int]$timeout = 600 # ms
2023-11-08 13:44:17 +01:00
$queue = [System.Collections.Queue]::new()
foreach($hostname in $hostsArray) {
$ping = [System.Net.Networkinformation.Ping]::new()
2024-01-03 11:59:38 +01:00
$obj = @{ Host = $hostname; Ping = $ping; Async = $ping.SendPingAsync($hostname, $timeout) }
$queue.Enqueue($obj)
2023-11-08 13:44:17 +01:00
}
[string]$result = ""
while ($queue.Count -gt 0) {
2024-01-03 11:59:38 +01:00
$obj = $queue.Dequeue()
2023-11-08 13:44:17 +01:00
try {
2024-01-03 11:59:38 +01:00
if ($obj.Async.Wait($timeout) -eq $true) {
if ($obj.Async.Result.Status -ne "TimedOut") {
$result += "$($obj.Host) "
2023-11-08 13:44:17 +01:00
}
continue
}
} catch {
2024-01-03 11:59:38 +01:00
if ($obj.Async.IsCompleted -eq $true) { continue }
2023-11-08 13:44:17 +01:00
}
2024-01-03 11:59:38 +01:00
$queue.Enqueue($obj)
2023-11-08 13:44:17 +01:00
}
Write-Progress -completed "Done."
Write-Host "✅ Up: $($result)"
2023-11-08 13:44:17 +01:00
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}