首页 > 解决方案 > PowerShell Loop Ping 在线状态

问题描述

我正在尝试修改 Powershell 来完成以下工作,但我遇到了一些错误。

我的目标是从 Powershell 窗口监控多台服务器的在线状态。我需要打开一个 Powershell 并从 Powershell 窗口运行 ps1 脚本,然后监视在线状态结果。

1. 从 hostname.txt 的列表中 ping 服务器
2. 如果服务器可 ping 且在线返回主机名和 ip 为绿色
3. 如果服务器超时返回主机名和 ip 为红色
4. 循环回第一台服务器并再次 ping

请帮助。谢谢你 !

$name=Get-content "c:\temp\hostname.txt"

foreach($name in $names) {
if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue) {
Write-Host "$name is up" -foregroundColor Green
$output+="$name is up,"+"'n"
}

else {

Write-Host "$name is up" -foregroundColor Red
$output+="$name is down,"+"'n"
}
}

标签: powershell

解决方案


如果您希望它永久重复,请将整个内容包装在一个while($true){...}循环中:

while($true){
    $names = Get-content "c:\temp\hostname.txt"

    foreach ($name in $names) {
        if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue) {
            Write-Host "$name is up" -foregroundColor Green
            $output += "$name is up," + "'n"
        }
        else {
            Write-Host "$name is up" -foregroundColor Red
            $output += "$name is down," + "'n"
        }
    }
}

如果要显示解析的 IP 地址,请确保将输出保存Test-Connection到变量:

if($ping = Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
    Write-Host "$name [IP: $($ping.ProtocolAddress)] is up" -ForegroundColor Green
    $output += "$name [IP: $($ping.ProtocolAddress)] is up `n"
}

推荐阅读