Powershell将txt文件的列转换为JSON格式



我有以下输出(在文件.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

我需要CPU的数量(第一列)和最后一个(%空闲)在Json中解析。

例如

[
{
"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?提前感谢

您需要构建对象([pscustomobject]实例)与.Num.Data属性以获得您想要的JSON格式:

Get-Content $file | 
ForEach-Object {
# Extract the column values of interest...
$cpu, $idle = (-split $_)[1, -1]
# ... and use them to construct and output a custom object.
[pscustomobject] @{
Num = $cpu
Data = $idle
}
} | ConvertTo-Json
  • 我使用了-split操作符的一元形式,通过空格的非空运行来分割每行(同时忽略前导和尾随空格)。

  • 由于%idle列是最后一个列,因此可以用索引-1来引用它。

  • $cpu, $idle = ...是一个多赋值,它将两个数组元素分别赋值给指定的变量。

  • [pscustomobject] @{ ... }是通过哈希表(@{ ... })构建[pscustomobject]实例的语法糖。[1]


[1]注意,当使用这种语法时,实际上没有构造单独的哈希表。此外,与真哈希表不同,在本例中指定的属性(键)顺序是保留的

最新更新