Reputation: 15
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>
Upvotes: 0
Views: 58
Reputation: 1999
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)
Upvotes: 3