You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell后台检测网络计算机在线状态并通知的实现问询

当然可以用PowerShell实现这个需求!

你的思路已经抓准了核心:后台循环检测主机可达性,状态变化时触发通知。下面我会把你的伪代码转换成可运行的PowerShell实现,还会优化一些细节避免重复通知。

核心实现步骤

  1. 用PowerShell类封装主机信息、在线状态和通知回调
  2. 初始化需要监控的主机集合
  3. 编写后台循环检测逻辑,用Test-Connection替代ping(更适合PowerShell的对象化操作)
  4. 仅当主机从离线切换到在线时触发通知,避免重复提醒

完整代码示例

1. 定义主机类

class Computer {
    [string]$Name          # 主机名/IP地址
    [bool]$IsOnline = $false # 当前在线状态
    [ScriptBlock]$OnOnline  # 上线时触发的回调函数

    # 构造函数,初始化主机名
    Computer([string]$hostName) {
        $this.Name = $hostName
        # 默认回调:控制台输出
        $this.OnOnline = { Write-Host "[$(Get-Date -Format 'HH:mm:ss')] 主机 $($this.Name) 上线了!" -ForegroundColor Green }
    }
}

2. 初始化监控列表

# 添加需要监控的主机,支持IP或主机名
$collectionOfComputers = @(
    [Computer]::new("192.168.1.100"),
    [Computer]::new("company-server"),
    [Computer]::new("10.0.0.5")
)

# 也可以自定义特定主机的通知逻辑,比如弹出Windows消息框
$customNotify = {
    Add-Type -AssemblyName PresentationFramework
    [System.Windows.MessageBox]::Show("主机 $($this.Name) 已上线!", "监控提醒", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information)
}
# 给某个主机替换回调
$collectionOfComputers[1].OnOnline = $customNotify

3. 编写检测Worker函数

function Invoke-Worker {
    $checkInterval = 10 # 检测间隔(秒)
    while ($true) {
        foreach ($computer in $collectionOfComputers) {
            # 用Test-Connection检测主机,-Quiet直接返回布尔值,-Count 1减少检测耗时
            $currentStatus = Test-Connection -ComputerName $computer.Name -Count 1 -Quiet -ErrorAction SilentlyContinue

            # 仅当状态从离线→在线时触发通知
            if ($currentStatus -and -not $computer.IsOnline) {
                $computer.IsOnline = $true
                & $computer.OnOnline # 执行回调函数
            }
            # 更新离线状态(可选,用于日志输出)
            elseif (-not $currentStatus -and $computer.IsOnline) {
                $computer.IsOnline = $false
                Write-Host "[$(Get-Date -Format 'HH:mm:ss')] 主机 $($computer.Name) 已离线" -ForegroundColor Yellow
            }
        }
        Start-Sleep -Seconds $checkInterval
    }
}

4. 运行检测任务

如果想让脚本在后台运行不阻塞控制台,可以用PowerShell后台作业:

# 启动后台检测任务
$monitorJob = Start-Job -ScriptBlock ${function:Invoke-Worker}

# 查看任务输出(实时看通知)
Receive-Job -Job $monitorJob -Wait

# 停止后台任务(需要时)
Stop-Job -Job $monitorJob
Remove-Job -Job $monitorJob

关键细节说明

  • Test-Connection比原生ping命令更适合PowerShell,它返回结构化结果,-Quiet参数简化了可达性判断
  • 状态切换判断:避免了每次检测都触发通知,只有当主机从离线变为在线时才执行回调,减少干扰
  • 自定义回调:可以根据需求修改OnOnline脚本块,比如发送邮件、写入日志文件、调用企业微信机器人等

内容的提问来源于stack exchange,提问作者Th1sD0t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:17:33