2017-04-26 85 views
0

我有一個需要在用戶數據中編輯的.json文件,所以我將不得不使用powershell來完成此操作。 的JSON看起來是這樣的:使用powershell編輯.json文件

{ 
"EngineConfiguration": { 
    "PollInterval": "00:00:15", 
    "Components": [ 
     { 
      "Id": "CustomLogs", 
      "FullName": "AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch", 
      "Parameters": { 
       "LogDirectoryPath": "C:\\CustomLogs\\", 
       "TimestampFormat": "MM/dd/yyyy HH:mm:ss", 
       "Encoding": "UTF-8", 
       "Filter": "", 
       "CultureName": "en-US", 
       "TimeZoneKind": "Local" 
      } 
     } 
    ], 
    "Flows": { 
     "Flows": 
     [ 
      "(ApplicationEventLog,SystemEventLog),CloudWatchLogs" 
      ] 
     } 
    } 
} 

我想它看起來就像這樣 -

{ 
"EngineConfiguration": { 
    "PollInterval": "00:00:15", 
    "Components": [ 
     { 
      "Id": "CustomLogs", 
      "FullName": "AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch", 
      "Parameters": { 
       "LogDirectoryPath": "C:\\ProgramData\\Amazon\\CodeDeploy\\deployment-logs", 
       "TimestampFormat": "[yyyy-MM-dd HH:mm:ss.fff]", 
       "Encoding": "UTF-8", 
       "Filter": "", 
       "CultureName": "en-US", 
       "TimeZoneKind": "Local" 
      } 
     } 
    ], 
    "Flows": { 
     "Flows": 
     [ 
      "(ApplicationEventLog,SystemEventLog, CustomLogs),CloudWatchLogs" 
      ] 
     } 
    } 
} 

在自定義日誌參數方面,LogDirectoryPath和TimestampFormat已經都變了。另外,在Flows部分中,我已將「CustomLogs」添加到CloudWatch Group。

我試圖使其與代碼打交道的是這樣的:

$a = Get-Content 'C:\PATH\TO\file.json' -raw | ConvertFrom-Json 
$a.EngineConfiguration.Components[0].Parameters = '{"LogDirectoryPath": "","TimestampFormat": "[yyyy-MM-dd HH:mm:ss.fff]","Encoding": "UTF-8","Filter": "","CultureName": "en-US","TimeZoneKind": "Local"}' 
$a | ConvertTo-Json | set-content 'C:\PATH\TO\output.json' 

但是,這產生一個非常難看的輸出

{ 
"EngineConfiguration": { 
          "PollInterval": "00:00:15", 
          "Components": [ 
               "@{Id=CustomLogs; FullName=AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch; Parameters={\"LogDirectoryPath\": \"\",\"TimestampFormat\": \"[yyyy-MM-dd HH:mm:ss.fff]\",\"Encoding\": \"UTF-8\",\"Filter\": \"\",\"CultureName\": \"en-US\",\"TimeZoneKind\": \"Local\"}}", 
               "@{Id=CloudWatchLogs; FullName=AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch; Parameters=}" 
              ], 
          "Flows": { 
              "Flows": "(ApplicationEventLog,SystemEventLog),CloudWatchLogs" 
             } 
         } 
} 

有沒有更優雅的方式來做到這一點?任何建議將不勝感激。謝謝!

回答

2

嘗試使用-Depth開關ConvertTo-Json。默認情況下,該壓縮超出深度爲2的所有子元素的對象的字符串表示你已經看到:

"@{Id=CustomLogs; etc." 

通過指定一個更深的深度,你得到更多的像一個你想要的格式。將此與壓縮過多空白的東西組合如下:

((ConvertFrom-Json $a) | ConvertTo-Json -Depth 4) -replace ((" "*4)," ") 
0

使用正則表達式可以減少主要的空白。然而,這並不能真正產生你想要的重新格式化,漂亮的打印。

$a | ConvertTo-Json | % {$_ -replace "  "," "} | set-content 'output.json'