我有以下輸出(在檔案 .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 得到它?提前致謝
uj5u.com熱心網友回復:
您需要使用和屬性構造物件([pscustomobject]實體)以獲得所需的 JSON 格式:.Num.Data
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列是最后一列,因此可以使用 index 來參考它-1。$cpu, $idle = ...是一個多重賦值,將單獨回傳的兩個陣列元素分配給指定的變數。[pscustomobject] @{ ... }是[pscustomobject]通過哈希表(@{ ... })構造實體的語法糖。[1]
[1] 請注意,使用此語法時實際上并沒有構建單獨的哈希表。此外,與真正的哈希表不同,在這種情況下,指定的屬性(鍵)的順序被保留。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/338514.html
