PowerShell/docs/ping-host.md

85 lines
2.1 KiB
Markdown
Raw Normal View History

2024-11-08 12:38:20 +01:00
The *ping-host.ps1* Script
===========================
2024-03-27 17:36:59 +01:00
2024-11-08 12:35:11 +01:00
This PowerShell script pings the given host.
2024-03-27 17:36:59 +01:00
Parameters
----------
```powershell
2024-11-08 12:35:11 +01:00
/home/markus/Repos/PowerShell/scripts/ping-host.ps1 [[-hostname] <String>] [<CommonParameters>]
2024-03-27 17:36:59 +01:00
-hostname <String>
2024-11-08 12:35:11 +01:00
Specifies the hostname or IP address to ping (windows.com by default)
2024-03-27 17:36:59 +01:00
Required? false
Position? 1
Default value windows.com
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
```
Example
-------
```powershell
2024-11-08 12:35:11 +01:00
PS> ./ping-host.ps1 x.com
✅ x.com is up and running (11ms latency).
2024-03-27 17:36:59 +01:00
```
Notes
-----
Author: Markus Fleschutz | License: CC0
Related Links
-------------
https://github.com/fleschutz/PowerShell
Script Content
--------------
```powershell
<#
.SYNOPSIS
2024-11-08 12:35:11 +01:00
Pings a host
2024-03-27 17:36:59 +01:00
.DESCRIPTION
2024-11-08 12:35:11 +01:00
This PowerShell script pings the given host.
2024-03-27 17:36:59 +01:00
.PARAMETER hostname
2024-11-08 12:35:11 +01:00
Specifies the hostname or IP address to ping (windows.com by default)
2024-03-27 17:36:59 +01:00
.EXAMPLE
2024-11-08 12:35:11 +01:00
PS> ./ping-host.ps1 x.com
✅ x.com is up and running (11ms latency).
2024-03-27 17:36:59 +01:00
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
2024-11-08 12:35:11 +01:00
param([string]$hostname = "windows.com")
2024-03-27 17:36:59 +01:00
function GetPingLatency([string]$hostname) {
$hostsArray = $hostname.Split(",")
2024-11-08 12:35:11 +01:00
$tasks = $hostsArray | foreach { (New-Object Net.NetworkInformation.Ping).SendPingAsync($_,1500) }
2024-03-27 17:36:59 +01:00
[Threading.Tasks.Task]::WaitAll($tasks)
2024-11-08 12:35:11 +01:00
foreach($ping in $tasks.Result) { if ($ping.Status -eq "Success") { return $ping.RoundtripTime } }
return 1500
2024-03-27 17:36:59 +01:00
}
try {
2024-11-08 12:35:11 +01:00
[int]$latency = GetPingLatency($hostname)
if ($latency -eq 1500) {
Write-Host "⚠️ Host '$hostname' doesn't respond - check the connection or maybe the host is down."
exit 1
}
Write-Host "✅ $hostname is up and running ($($latency)ms latency)."
2024-03-27 17:36:59 +01:00
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
```
2024-11-08 12:40:31 +01:00
*(generated by convert-ps2md.ps1 as of 11/08/2024 12:40:21)*