简体   繁体   中英

Edit Json using powershell

I have a complex configuration file that i want to update using Powershell.

is there any helpful way i could achieve that.

I want to update SelectedCodes only.

the file:

<?xml version="1.0"?>
<Settings>
  <ServerIPAddress>192.168.150.128:8090</ServerIPAddress>
  <SettingString>
    {
      "StationName":"Testing",
      "LocationCode":12,
      "AskForMoreDetails":false,
      "IsLaptop":false,
      "SpecificDepartment":"",
      "SelectedCodes":[
          {
            "Id":16,
            "Name":"Code Blue",
            "HtmlColorCode":"#0000FF",
            "TextColorCode":"#ffffff",
            "DisplayOrderNumber":1
          },
          {
            "Id":19,
            "Name":"CCRT",
            "HtmlColorCode":"#3CB371",
            "TextColorCode":"#FFFFFF",
            "DisplayOrderNumber":3
          }
      ],
      "AreaCode":12
    }
  </SettingString>
  <StartUpLaunchSet>False</StartUpLaunchSet>
  <CodeRedId>27</CodeRedId>
</Settings>

you first have to create another code object like:

$additionalCode = [pscustomobject]@{
    Id='20'
    Name='Code Red'
    HtmlColorCode='#e83f3f'
    TextColorCode='#ffffff'
    DisplayOrderNumber='5'
}

to add this to your file we first have to read the file

$filePath = 'c:\path\to\file.xml'
[XML]$xmlObject = Get-Content -Path $filePath

convert the JSON part of the xml to PowerShell object

$settingJson = $xmlObject.Settings.SettingString | ConvertFrom-Json

add the previously created additional code object

$settingJson.SelectedCodes += $additionalCode

convert the JSON to string and store it back in the XML object

$settingString = $settingJson | ConvertTo-Json
$xmlObject.Settings.SettingString = $settingString.ToString()

save the XML document to file

$xmlObject.Save('c:\path\to\edited.xml')

or overwrite the file directly

$xmlObject.Save($filePath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM