#进程巡检
#题目
编写脚本找出当前系统中占用内存最高的 5 个进程,并把结果导出为 CSV 文件,便于后续分析。
#要求
- 使用
Get-Process获取进程信息。 - 按内存占用从高到低排序,取前 5 个。
- 导出字段包括进程 ID、进程名、内存占用和 CPU 时间。
- CSV 使用 UTF-8 编码,文件路径可以通过参数指定。
- 在 Windows、Linux、macOS 上都能运行。
#参考实现
inspect.ps1
param(
[string]$OutputPath = './top-processes.csv'
)
$top = Get-Process |
Sort-Object -Property WorkingSet64 -Descending |
Select-Object -First 5 -Property Id, ProcessName, WorkingSet64, CPU
$top | Format-Table -AutoSize
$top | Export-Csv -LiteralPath $OutputPath -NoTypeInformation -Encoding utf8
Write-Host "已导出:$OutputPath"
运行:
> ./inspect.ps1 -OutputPath ./top5.csv
Id ProcessName WorkingSet64 CPU
-- ----------- ------------ ---
4321 chrome 524288000 120.45
2180 Code 387973120 45.12
980 pwsh 104857600 8.73
3012 explorer 98304000 12.08
1456 svchost 65536000 3.21
#讲解
#Get-Process
Get-Process 返回进程对象。不同平台上可用的属性略有差异:
> Get-Process | Select-Object -First 1 | Get-Member
Id是进程 ID。ProcessName是进程名。WorkingSet64是工作集大小(字节),可近似表示内存占用。CPU是累计 CPU 时间(秒),部分平台上可能为空。- 需要按某个属性排序前,先确认该属性在当前平台有值。
#Sort-Object
Sort-Object -Property WorkingSet64 -Descending 按内存降序排列:
> Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 5
-First 5 在排序后截取前 5 条。注意顺序:应先排序再截取,否则得到的只是任意 5 个进程。
#Export-Csv
Export-Csv 把对象序列化为 CSV:
> $top | Export-Csv -Path ./top5.csv -NoTypeInformation -Encoding utf8
- 每个对象的属性对应一列,属性名作为表头。
-NoTypeInformation省略首行的类型信息;PowerShell 7 中该参数已经不再必要,但保留可以兼容旧脚本。-Encoding utf8保证中文进程名不乱码。PowerShell 7 默认使用 UTF-8,Windows PowerShell 5.1 默认使用 ANSI。-LiteralPath避免路径中的方括号等字符被当作通配符。
导入检查:Import-Csv -LiteralPath ./top5.csv | Format-Table。
如果需要把内存字节数显示为 MB,可以在导出前新增计算属性:
$top | Select-Object Id, ProcessName,
@{Name = 'MemoryMB'; Expression = { [math]::Round($_.WorkingSet64 / 1MB, 1) } } |
Export-Csv -Path ./top5.csv -NoTypeInformation -Encoding utf8