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) { ... }循环块后,脚本会按顺序完成以下操作一次后自动终止:
- 读取
Computers.txt中的服务器列表 - 遍历每个服务器采集CPU、内存数据
- 格式化输出内容并写入
filetest.csv文件
内容的提问来源于stack exchange,提问作者user23337292
相关产品推荐
相关产品推荐

