前言
在先前撰寫的 PowerShell - 參照清單快速 Ping 特定的 Windows 主機 文章中,主要是針對特定的 Windows 主機,先確認是否有網域環境中的電腦帳號,然後才執行 ping 的動作。本文的需求則有些微不同,希望可以持續 ping 特定的主機 (Windows 和 Linux),然後 ping 失敗的主機會在 PowerShell 視窗中用「紅色字體」顯示之外,也把 ping 失敗的時間和主機名稱寫入 log 當中,所以本篇筆記就出現了。執行結果
首先,請在 PowerShell 所在路徑中,建立
Ping_hosts.txt
文字檔案,將要持續 ping 的主機清單寫入其中。
執行時,首先會先用「紫色字體」顯示目前的時間,以及 ping 主機的總數 (讀取主機清單),然後透過
Test-Connection
執行 ping 特定主機的動作 (以白色字體顯示),但是 ping
失敗的主機先不顯示,否則會讓整個 PowerShell 執行視窗的結果亂掉
(錯誤訊息噴太多了 😂),接著再用「紅色字體」顯示 ping 失敗的主機,同時把 ping 失敗的時間和主機名稱寫入 log 當中 (<今天日期>_ping_failed_hosts.txt),最後用「黃色字體」顯示休息 60 秒之後,再繼續 ping 的動作。
Keep_Ping_Hosts.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ================================================================== | |
# Author: Weithenn Wang (weithenn at weithenn.org) | |
# Version: v0.3 - Auguest 10, 2021 | |
# Description: Keep ping connectivity by hosts list | |
# ================================================================== | |
# Get hosts list | |
$Today = Get-Date -Format "yyyyMMdd" | |
$Ping_hosts = Get-Content -Path ".\Ping_hosts.txt" | |
$Number_of_hosts = (Get-Content -Path ".\Ping_hosts.txt").Count | |
$Ping_interval = 60 | |
# Keep the ping host to rest for 60 seconds | |
while ($true){ | |
Write-Host "===== $(Get-Date) - Starting to ping $Number_of_hosts hosts =====" -ForegroundColor Magenta | |
# Ping all hosts, but ignore error hosts | |
Test-Connection -ComputerName $Ping_hosts -Count 1 -ErrorAction SilentlyContinue| Format-Table -AutoSize | |
# Write the failed hosts to the log | |
foreach ($Hosts in $Ping_hosts){ | |
If (Test-Connection -ComputerName $Hosts -Count 1 -Quiet){ | |
} else { | |
Write-Host "$Hosts - ping and hostname resolution failed!" -ForegroundColor Red | |
"$(Get-Date) - $Hosts" | Out-File -FilePath ".\$($Today)_ping_failed_hosts.txt" -Append | |
} | |
} | |
Write-Host "" | |
Write-Host "===== Resume ping after $Ping_interval seconds =====" -ForegroundColor Yellow | |
Start-Sleep -s $Ping_interval; | |
Clear-Host; | |
} |