服务器监控powershell脚本

问题描述

我编写了一个用于服务器监控的 PowerShell 脚本。我在 Google Cloud Platform 上创建了一个服务器。我的服务器/实例外部 IP 是 34.72.154.186 (http://34.72.154.186/)。这是我的 PowerShell 脚本:

$content = Get-Content C:\Users\Samiddha\Desktop\ServerLists.txt
foreach ($line in $content)
{
    Test-Connection $line -Count 2 -ErrorAction SilentlyContinue > ./junk
    if ($? -eq "True")
    {
        Write-Host "$line => OK"
    }
    else
    {
        Write-Host "$line => NOT-OK"
    }
}

此脚本在服务器运行或启动时返回输出 OK。当我使用 systemctl stop httpd 命令停止服务器时,这个脚本给了我输出 OK,但为什么呢?它应该给出输出 NOT-OK。但是,如果我通过点击 Google Cloud 仪表板中的 STOP 按钮关闭服务器,此脚本会给出输出 NOT-OK。我应该对脚本做哪些修改,以便当我通过 NOT-OK 命令停止服务器时该脚本给我输出 systemctl stop httpd

解决方法

这是我的尝试。

    $content = Get-Content C:\Users\Samiddha\Desktop\ServerLists.txt
    foreach ($line in $content){
      if (Test-Connection $line -Count 2 -ErrorAction SilentlyContinue) {
        Write-Host "$line => OK"
      }else{
        Write-Host "$line => NOT-OK"
      }
    }

屏幕输出

    PS C:\Users\Tech\desktop\i-net> .\test
    192.168.43.38 => OK
    192.168.43.37 => NOT-OK
    34.72.154.186 => NOT-OK
    PS C:\Users\Tech\desktop\i-net>

第一个ip是我的服务器 第二没什么 第三个是你提供的ip。我想它没有起来

您还可以将 -ForegroundColor Red 添加到第 8 行的末尾,这将使停机的服务器在视觉上弹出。即

    Write-Host "$line => NOT-OK" -ForegroundColor Red