PowerShell/scripts/ping-host.ps1

37 lines
1.2 KiB
PowerShell
Raw Normal View History

2024-10-01 15:11:03 +02:00
<#
2024-03-23 11:57:48 +01:00
.SYNOPSIS
2024-11-04 15:08:49 +01:00
Pings a host
2024-03-23 11:57:48 +01:00
.DESCRIPTION
2024-11-04 15:08:49 +01:00
This PowerShell script pings the given host.
2024-03-23 11:57:48 +01:00
.PARAMETER hostname
2024-12-04 11:24:21 +01:00
Specifies the hostname or IP address to ping (x.com by default)
2024-03-23 11:57:48 +01:00
.EXAMPLE
2024-11-04 15:08:49 +01:00
PS> ./ping-host.ps1 x.com
2025-01-03 11:48:36 +01:00
Host 'x.com' with 20ms latency at IP 104.244.42.1 is up 👍
2024-03-23 11:57:48 +01:00
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
2024-12-04 11:24:21 +01:00
param([string]$hostname = "x.com")
2024-03-23 11:57:48 +01:00
try {
2024-12-07 15:09:54 +01:00
$remoteHosts = $hostname.Split(",")
2025-01-08 21:03:41 +01:00
$tasks = $remoteHosts | foreach { (New-Object Net.NetworkInformation.Ping).SendPingAsync($_,5000) }
2024-12-07 15:09:54 +01:00
[Threading.Tasks.Task]::WaitAll($tasks)
foreach($ping in $tasks.Result) {
if ($ping.Status -eq "Success") {
2025-01-03 11:48:36 +01:00
Write-Output "✅ Host '$hostname' with $($ping.RoundtripTime)ms latency at IP $($ping.Address) is up 👍"
2024-12-07 15:09:54 +01:00
exit 0 # success
2024-12-28 16:46:20 +01:00
} else {
Write-Output "⚠️ No reply from '$hostname' (IP $($ping.Address)) - check the connection or maybe the host is down."
exit 1
2024-12-07 15:09:54 +01:00
}
}
2024-12-28 16:46:20 +01:00
Write-Output "⚠️ No reply from host '$hostname' - check the connection or maybe the host is down."
2024-12-07 15:09:54 +01:00
exit 1
2024-03-23 11:57:48 +01:00
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}