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

PowerShell脚本循环获取服务器CPU/内存,需改为仅执行一次

解决PowerShell脚本无限循环问题,改为仅执行一次

原脚本的核心问题是使用了while ($true)无限循环语句,导致代码持续重复执行。只需移除这个循环包裹,就能让脚本仅执行一次后停止。

修改后的完整代码:

$computers = Get-Content -Path F:\data\Computers.txt

$output = foreach ($computer in $computers) {
    $date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $totalRam = (Get-CimInstance Win32_PhysicalMemory -ComputerName $computer | Measure-Object -Property capacity -Sum).Sum
    $cpuTime = (Get-Counter '\Processor(_Total)% Processor Time' -ComputerName $computer).CounterSamples.CookedValue
    $availMem = (Get-Counter '\Memory\Available MBytes' -ComputerName $computer).CounterSamples.CookedValue

    "{0} {1} \> CPU: {2:#.###}%, Avail. Mem: {3:N0}MB ({4:#.#}%)" -f $computer,$date,$cputime,$availMem,(104857600 * $availMem / $totalRam)
}
$output | Out-File "f:\data\filetest.csv" -Append

说明

移除while ($true) { ... }循环块后,脚本会按顺序完成以下操作一次后自动终止:

  1. 读取Computers.txt中的服务器列表
  2. 遍历每个服务器采集CPU、内存数据
  3. 格式化输出内容并写入filetest.csv文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:33:20