我正在尝试从Powershell对象生成JSON字典,其格式默认为ConvertTo-Json cmdlet不提供。
例如ConvertTo-Json
将采用
(get-counter '\Process(*)\% Processor Time').CounterSamples | select InstanceName, CookedValue
如下所示:
InstanceName CookedValue
------------ -----------
idle 92.02923730929
process1 3
process2 1
process3 0
process4 2
process5 0
process6 2
process7 0
.... ....
并生成如下所示的JSON对象:
[
{
"InstanceName": "idle",
"CookedValue": 92.02923730929
},
{
"InstanceName": "process1",
"CookedValue": 3
},
{
"InstanceName": "process2",
"CookedValue": 1
},
...
]
是否可以像这样格式化JSON对象?
{
idle: 92.02923730929,
process1: 3,
process2: 1,
process3: 0,
process4: 2,
process5: 0,
}
谢谢
答案 0 :(得分:1)
创建一个具有由示例属性值组成的属性的新对象:
$properties = @{}
(Get-Counter '\Process(*)\% Processor Time').CounterSamples |ForEach-Object {
$properties[$_.InstanceName] = $_.CookedValue
}
New-Object psobject -Properties $properties |ConvertTo-Json
由于您可能有多个具有相同进程名称的实例,因此您可能希望从计数器Path
中提取进程名称和实例编号:
$properties = @{}
(Get-Counter '\Process(*)\% Processor Time').CounterSamples |ForEach-Object {
$InstanceName = if($_.Path -match 'process\((.*#\d+)\)'){
$Matches[1]
}
else {
$_.InstanceName
}
$properties[$InstanceName] = $_.CookedValue
}
New-Object psobject -Property $properties |ConvertTo-Json
答案 1 :(得分:0)
只需将其传输到ConvertTo-Json
(get-counter '\Process(*)\% Processor Time').CounterSamples | select InstanceName, CookedValue | ConvertTo-Json
我无法回答您重新格式化JSON输出格式的第二个问题