0

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>
2
  • What do you want it to update to? Commented Jan 24, 2021 at 5:47
  • I want to add more SelectedCodes Commented Jan 24, 2021 at 5:56

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@SaadAldulaijan please mark the answer as such

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.