我使用下面的命令来生成下面的输出
$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"
}
]发布于 2014-05-27 14:40:19
我会使用[Regex]静态方法Replace
$Json = $VMHost | ConvertTo-Json
[regex]::Replace(
$Json,
'(?<=")(\w+)(?=":)',
{
$args[0].Groups[1].Value.ToLower()
}
)发布于 2014-05-27 06:32:56
将此代码放在$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"发布于 2014-05-27 12:09:50
这不是最好的解决方案,而是等待更好的解决方案的拐杖。
# Get the JSON text
$JSON = $VMHost | ConvertTo-Json
$JSON.Split("`n") | % {if($_ -match "(.*):(.*)"){$_ -replace '(.*):(.*)',"$($matches[1].ToLower()):$($matches[2])"}else{$_}}我使用正则表达式将所有键转换为小写,这必须用各种JSON进行测试
也许有人能提供更好的语法。
https://stackoverflow.com/questions/23878240
复制相似问题