如何使用PowerShell更新JSON文件

时间:2016-03-08 10:46:16

标签: json powershell powershell-v3.0

我有一个json文件mytest.json,如下所示我想使用PowerShell script更新值

update.json

{
    "update": [
        {
            "Name": "test1",        
            "Version": "2.1"
        },
        {
            "Name": "test2",        
            "Version": "2.1"
        }   
    ]
}

我想编写一个PowerShell脚本if Name=="test1" I want to update Version= "3" 我怎么能用参数做到?

2 个答案:

答案 0 :(得分:58)

这是一种方式:

$a = Get-Content 'D:\temp\mytest.json' -raw | ConvertFrom-Json
$a.update | % {if($_.name -eq 'test1'){$_.version=3.0}}
$a | ConvertTo-Json -depth 32| set-content 'D:\temp\mytestBis.json'

根据@FLGMwt和@mikemaccana,我使用ConvertTo-Json改进-depth 32,因为默认深度值为2,对于深度大于2的对象,您将收到类信息,无论对象如何。

答案 1 :(得分:5)

我也遇到过同样的问题。我想更改以下 JSON 文件的记录

{
"SQS_QUEUE_URL":  "https://que-url.com/server1",
"SQS_EVENTS_QUEUE_URL":  "https://events-server.com/server1/development_events",
"REGION":  "region1",
"BUCKET":  "test-bucket",
"AE_WORK_PATH":  "C:\\workpath\\path1",
"ENV":  "env"

}

最后,我设法找到了从 Powershell 生成 JSON 文件的最简单方法。

$json = Get-Content "c:\users\bharat.gadade\desktop\test.json" | ConvertFrom-Json 
$json.SQS_QUEUE_URL = "https://que-url.com/server2"
$json.SQS_EVENTS_QUEUE_URL = "https://events-server.com/Server2/development_events"
$json.REGION = "region1 "
$json.BUCKET = "test-bucket"
$json.AE_WORK_PATH = "C:\workpath\path1"
$json.ENV = "env"
$json | ConvertTo-Json | Out-File "c:\users\bharat.gadade\desktop\test.json"