【发布时间】:2021-12-11 22:06:13
【问题描述】:
我有以下输出(在文件 .txt 中)
Average: CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
Average: all 0.21 0.00 0.08 0.00 0.00 0.00 0.00 0.00 0.00 99.71
Average: 0 1.01 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 98.99
Average: 1 0.00 0.00 0.52 0.00 0.00 0.00 0.00 0.00 0.00 99.48
我需要在 Json 中解析 CPU 的数量(第一列)和最后一个(%idle)。
例如
[
{
"Num": "all",
"Data": "99.71"
},
{
"Num": "0",
"Data": "98.99"
},
{
"Num": "1",
"Data": "99.48"
}
]
但我得到以下输出:
[
"Num_all 99.71",
"Num_0 98.99",
"Num_1 99.48"
]
Json 是有效的,但不幸的是这不是预期的输出。
我的代码:
$file = Join-Path $PSScriptRoot cpu.txt
#Create .temp file with the stats
$cpu_stats = mpstat -P ALL 1 2 | grep Average > $file
#Print the first column (cpu num) and 11th (Average CPU)
$info_json = Get-Content $file | Select-object -skip 1| Foreach {"Num_$(($_ -split '\s+',12)[1,11])"} | ConvertTo-Json
#Print result (Json)
Write-Output $info_json
我如何使用 PowerShell 来获得它? 提前致谢
【问题讨论】:
标签: json powershell parsing