-1

我每个月都会执行一次维护例行程序,对大约 15 台设备进行 ping 操作。我只是想运行一个执行以下操作的命令脚本。

  • 调用一个 txt 文件(我已经填充了 15 个左右的 IP 地址)
  • 打开 15 个单独的命令窗口并运行连续 PING(即 Start cmd ping 10.1.1.5 /t)
  • 层叠所有 15 个单独的窗口
  • 这就是问题所在......如果设备回复返回 ping,我希望屏幕输出具有黑色 txt 和绿色背景以显示积极响应。如果设备超时,那么我希望屏幕输出具有黑色 txt 和红色背景来表示和发出。
4

1 回答 1

0

这需要一些修补(因为我不熟悉 power shell),但这是结果。

我有 3 个单独的文件:

  1. 包含要 ping 的所有 IP 地址的文件。(server_ip_addresses.txt)
  2. 一个 ping 脚本,它在循环中 ping 每个 IP 地址。(ping_window.ps1)
  3. 读取 IP 地址文件并在单独的窗口中启动 ping 脚本的主脚本。(shell.ps1)

源文件:

将它们全部放在同一个目录中。

server_ip_addresses.txt

在每一行定义 1 个 IP 地址,例如:

8.8.8.8
1.1.1.1
172.16.0.1

(1.DNS google,2.DNS cloudflare,3.在我的网络中不可路由的私有 IP 地址)

ping_window.ps1

# function to color the BackGround and ForeGround of the shell
# https://stackoverflow.com/questions/18685772/how-to-set-powershell-background-color-programmatically-to-rgb-value
function Set-ConsoleColor ($bc, $fc) {
    $Host.UI.RawUI.BackgroundColor = $bc
    $Host.UI.RawUI.ForegroundColor = $fc
    Clear-Host
}

$loop_count = 0
while($true) {
    $loop_count = $loop_count + 1
    $Host.UI.RawUI.WindowTitle = "ping $Args --- loop: $loop_count"
    
    # execute ping
    Write-Output "$Args"
    $job = ping $Args
    
    # check if we have an error message
    if($job -match "Destination host unreachable") {
        Set-ConsoleColor "red" "black"
    } elseif($job -match "TTL Expired in Transit") {
        Set-ConsoleColor "red" "black"
    } elseif($job -match "Request Timed Out") {
        Set-ConsoleColor "red" "black"
    } elseif($job -match "Unknown Host") {
        Set-ConsoleColor "red" "black"
    } else {
        Set-ConsoleColor "green" "black"
    }
    
    Write-Output "Result: $job"
}

外壳.ps1

# run with: "powershell -ExecutionPolicy Bypass -File .\shell.ps1"

Write-Output $Args[0]

$stream_reader = New-Object System.IO.StreamReader{server_ip_addresses.txt}
$line_number = 1
while (($current_line =$stream_reader.ReadLine()) -ne $null)
{
    Invoke-Expression 'cmd /c start powershell -NoExit .\ping_window.ps1 $current_line'
    $line_number++
}

执行和输出

因为我没有以管理员身份运行,所以我不得不绕过“执行策略”:

powershell -ExecutionPolicy Bypass -File .\shell.ps1

对于 server_ip_addresses.txt 中的每个 IP 地址,都会创建一个新的 power shell 窗口。(我相信它们默认是级联的)

我们不使用 ping -t 标志连续运行它,而是发送 4 个 ping。然后我们读取输出,适当地为 shell 着色并再次 ping。使用窗口标题中的循环计数器,您可以跟踪执行 ping 命令的次数。

要检查我们是否有错误消息(并将 shell 背景涂成红色),脚本会尝试匹配以下子字符串:

  • “目标主机不可达”
  • “TTL 在运输中过期”
  • “请求超时”
  • “未知主机”

如果未找到任何消息,则背景设置为绿色。它还可以适应使用不同的背景颜色和/或字体颜色。只需更改Set-ConsoleColorping_window.ps1 中的参数即可

使用当前 server_ip_addresses.txt 我得到以下输出: 在此处输入图像描述

要停止执行,我认为您必须先停止脚本然后关闭窗口。否则它们会继续在后台运行。

于 2021-03-14T22:54:55.090 回答