请求优化完善获取进程信息的PowerShell脚本
PowerShell脚本实现指定格式的进程信息输出
以下是简化后的PowerShell脚本,可输出符合要求格式的进程信息,同时补充了CPU和内存信息的获取逻辑:
Get-Process | ForEach-Object { $currentTime = Get-Date -Format "yyyyMMdd HH:mm" # 计算进程平均CPU使用率(保留1位小数) $cpuUsage = if ($_.CPU) { [math]::Round($_.CPU / (Get-Date - $_.StartTime).TotalSeconds, 1) } else { 0.0 } # 转换内存占用为MB并取整 $memUsage = [math]::Round($_.WorkingSet / 1MB) # 获取完整命令行(含参数),无命令行时显示进程路径 $commandLine = $_.CommandLine ?? $_.Path # 按指定格式输出 "$currentTime - pid: $($_.Id) - cpu: $cpuUsage % - mem: $memUsage MB - $commandLine" }
关键逻辑说明
- 时间格式化:通过
Get-Date -Format "yyyyMMdd HH:mm"直接生成要求的时间字符串,无需额外拼接操作。 - CPU使用率计算:
Get-Process返回的CPU属性是进程启动以来的总CPU耗时,除以进程运行时长(当前时间与启动时间的差值)得到平均使用率,用[math]::Round控制小数位数。 - 内存占用获取:
WorkingSet属性对应进程当前使用的物理内存(字节),除以1MB转换为兆字节单位后取整。 - 命令行参数获取:使用空值合并运算符
??优先取CommandLine属性(含启动参数),为空时回退到进程路径Path。 - 简化实现:用
ForEach-Object直接遍历进程集合,避免冗余变量,代码更简洁高效。
实时CPU使用率优化(可选)
如果需要更精准的实时CPU使用率(而非进程启动以来的平均值),可通过两次采样计算差值实现:
# 第一次采样 $processSnapshot1 = Get-Process | Select-Object Id, CPU, StartTime, WorkingSet, CommandLine, Path Start-Sleep -Seconds 1 # 第二次采样 $processSnapshot2 = Get-Process | Select-Object Id, CPU foreach ($p1 in $processSnapshot1) { $p2 = $processSnapshot2 | Where-Object Id -eq $p1.Id if ($p2) { $currentTime = Get-Date -Format "yyyyMMdd HH:mm" # 计算1秒内的CPU使用率变化 $cpuUsage = [math]::Round($p2.CPU - $p1.CPU, 1) $memUsage = [math]::Round($p1.WorkingSet / 1MB) $commandLine = $p1.CommandLine ?? $p1.Path "$currentTime - pid: $($p1.Id) - cpu: $cpuUsage % - mem: $memUsage MB - $commandLine" } }
内容的提问来源于stack exchange,提问作者Martijn van den Boom
相关产品推荐
相关产品推荐

