powershell - 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"
}
}
解决方案
如果您希望它永久重复,请将整个内容包装在一个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"
}
推荐阅读
- python - Text.insert(tk.INSERT ...) 方法在 Python 中无法正常工作
- c# - 用户控件库中的依赖属性始终为空
- ios - 在 iOS 13 和 xcode 11 中,tableview 单元格的“setSelected”方法不返回完美的单元格大小
- python-3.x - 在while循环中打印额外的逗号 - Python
- python - 如何加快python pyinstaller生成的可执行文件的执行过程?
- c# - c#如何检测控制台stdin是否是终端
- kubernetes - 带有证书管理器和 Traefik 入口的 404 挑战响应
- c - 我正在为竞争激烈的编程平台编写此 C 代码,并且想知道在哪里可以改进代码以克服 SIGTSTP 错误?
- python - Pandas 中的布尔和索引切片
- java - KafkaMessageListenerContainer 与 ConcurrentMessageListenerContainer