我使用下面的命令生成以下输出
$VMHost | ConvertTo-json | Out-File -encoding "UTF8" -FilePath ".\$VMHostName.report"
但我需要所有小写和值的键,如下所示
"HostNumaStatus": [
{
"ComputerName": "TEMSA10",
"MemoryAvailable": 3119,
"MemoryTotal": 6075,
"NodeId": 0,
"ProcessorsAvailability": "35 41 56 58"
}
]
到
"hostnumastatus": [
{
"computername": "TEMSA10",
"memroyavailable": 3119,
"memroytotal": 6075,
"nodeid": 0,
"processoravailability": "35 41 56 58"
}
]
答案 0 :(得分:3)
我会使用[Regex]
静态方法Replace
:
$Json = $VMHost | ConvertTo-Json
[regex]::Replace(
$Json,
'(?<=")(\w+)(?=":)',
{
$args[0].Groups[1].Value.ToLower()
}
)
答案 1 :(得分:1)
将它放在$ VMHost和ConvertTo-JSON之间。
Select -Property @{N='computername';E={$_.ComputerName}}, @{N='memoryavailable';E={$_.MemoryAvailable}}, @{N='memorytotal';E={$_.MemoryTotal}}, @{N='nodeid';E={$_.NodeId}}, @{N='processorsavailability';E={$_.ProcessorsAvailability}}
由于列不是静态的,请尝试:
$cols = $VMHost | select * | Get-Member | ForEach-Object {@{N=$_.Name.ToLower();E=$_.Name}}
$VMHost | Select -Property $cols | ConvertTo-Json | Out-File -encoding "UTF8" -FilePath ".\$VMHostName.report"
我真的想在转换之前修改对象,但这样可以获得您之后的最终结果:
# Get the JSON text
$JSON = $VMHost | ConvertTo-Json
# Loop through each line of the JSON output
$JSON.Split("`n") | ForEach-Object {
# Split the line on the ":", grab the first portion, and trim the space
$value = $_.Split(":")[0].Trim()
# Check to see if both the start and end characters are quotes (these should be the key fields)
if (($value.Substring(0,1) -eq "`"") -and ($value.Substring($value.Length-1,1) -eq "`"")) {
# If it's a key make it lowercase
$_.Replace($value,$value.ToLower())
} else {
# Otherwise leave it as-is
$_
}
# Output
} | Out-File -encoding "UTF8" -FilePath ".\$VMHostName.report"
答案 2 :(得分:0)
这不是最好的解决方案,而是等待更好的
的拐杖# Get the JSON text
$JSON = $VMHost | ConvertTo-Json
$JSON.Split("`n") | % {if($_ -match "(.*):(.*)"){$_ -replace '(.*):(.*)',"$($matches[1].ToLower()):$($matches[2])"}else{$_}}
我使用正则表达式将所有键转换为小写,必须使用各种JSON进行测试
也许有人可以提供更好的语法。
答案 3 :(得分:0)
这对我来说效果很好。希望有帮助。
$data | ConvertTo-Json |Out-File "jsonfile.json"
(Get-Content -Path ".\jsonfile.json" -Raw).ToLower() |Out-File "jsonfile.json" -force -Encoding "UTF8"