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

多Windows系统进程CPU时间监控脚本:跨机与导出需求

多Windows机器进程CPU监控脚本(支持CSV导出)

以下是修改后的脚本,解决单机器限制和数据导出问题,同时保留你原有的CPU使用率计算逻辑:

# 配置参数
$targetComputers = @("PC-01", "PC-02", "localhost") # 替换为你的目标机器名/IP
$sampleInterval = 5 # 采集间隔(秒)
$outputPath = ".\ProcessCpuMonitor.csv"

# 初始化CSV文件(仅第一次运行时写入表头)
if (-not (Test-Path $outputPath)) {
    [PSCustomObject]@{
        Timestamp     = Get-Date
        ComputerName  = ""
        ProcessName   = ""
        CpuUsage      = 0
        RawCookedValue = 0
    } | Export-Csv -Path $outputPath -NoTypeInformation -Encoding UTF8
}

# 循环采集数据
while ($true) {
    $currentTime = Get-Date
    foreach ($computer in $targetComputers) {
        try {
            # 获取远程/本地进程CPU计数器
            $counterData = Get-Counter -ComputerName $computer '\Process(*)\% Processor Time' -ErrorAction Stop | 
                Select-Object -ExpandProperty CounterSamples | 
                Where-Object { $_.InstanceName -notmatch "^(idle|_total|system)$" }

            foreach ($sample in $counterData) {
                # 计算实际CPU使用率(单核心占比)
                $cpuUsage = ($sample.CookedValue / 100 / (Get-WmiObject -Class Win32_Processor -ComputerName $computer).NumberOfLogicalProcessors) * 100

                # 构造输出对象
                [PSCustomObject]@{
                    Timestamp     = $currentTime
                    ComputerName  = $computer
                    ProcessName   = $sample.InstanceName
                    CpuUsage      = [math]::Round($cpuUsage, 2)
                    RawCookedValue = $sample.CookedValue
                } | Export-Csv -Path $outputPath -Append -NoTypeInformation -Encoding UTF8
            }

            # 输出实时信息(可选)
            Write-Host "[$currentTime] 已采集 $computer 的进程CPU数据"
        }
        catch {
            Write-Warning "[$currentTime] 无法采集 $computer 的数据: $_"
        }
    }
    Start-Sleep -Seconds $sampleInterval
}

关键改进说明

  • 多机器支持:通过-ComputerName参数指定目标机器,循环遍历所有待监控设备
  • CSV数据持久化:使用Export-Csv -Append将每次采集的数据追加到文件,保留完整时间序列
  • 增强数据维度:添加Timestamp(采集时间)、ComputerName(机器标识)字段,方便后续跨机器分析
  • 准确CPU计算:通过Win32_Processor获取目标机器的逻辑核心数,避免原脚本依赖本地环境变量导致远程计算错误的问题
  • 错误处理:捕获远程连接失败的异常,避免单台机器故障导致整个脚本终止

使用前准备

  • 确保所有目标机器已开启WinRM服务(可在目标机器执行Enable-PSRemoting -Force开启)
  • 运行脚本的账号需要具备目标机器的管理员权限
  • 若使用IP地址监控,需确保目标机器防火墙允许WinRM端口(默认5985/5986)

停止脚本

按下 Ctrl + C 即可终止循环采集

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:35:18