How to modify/create values in XML files using PowerShell?
I would like to know if is it possible to modify/create values in XML files using PowerShell. Basically I'm interested in:
- Modify values in the XML file or create them if they don't exist (i.e. I need to search the item, create if not exists and modify the value)
- Deal with different XML syntax in the same XML file like those ones:
Syntax 1:
<settings> <setting id="Location2" value="Barcelona, Spain"/> <setting id="Location2id" value="zmw:00000.1.08181"/> </settings>
Syntax 2:
<settings> <musicplayer> <crossfade>0</crossfade> <queuebydefault>false</queuebydefault> </musicplayer> </settings>
Syntax 3:
<settings> <skinsettings> <setting type="bool" name="skin.confluence.HomepageHideRecentlyAddedVideo">false</setting> </skinsettings> </settings>
Any help would be very appreciated.
Thanks.
PowerShell fully supports dealing with XML files.
For example, if we take the first blurb you supplied and just paste it into an XML file named settings.xml
in folder "C:\blah", you could get the ID of each setting as such:
[xml]$myXML = Get-Content C:\blah\settings.xml
$myXML.settings.setting.id
Which returns:
Location2
Location2id
And
$myXML.settings.setting.value
returns:
Barcelona, Spain
zmw:00000.1.08181
If we replace the XML file contents with the blurb you provided in Syntax #2:
[xml]$myXML = Get-Content C:\blah\settings.xml
$myXML.settings.musicplayer.crossfade
returns:
0
To read crossfade
, change it (to 2), and save back:
[xml]$myXML = Get-Content C:\blah\settings.xml
$myXML.settings.musicplayer.crossfade = 2
$myXML.Save("C:\blah\settings.xml")
Edit after comments:
To change the XML elements themselves (as in the Barcelona example) is a little trickier, because you're editing the XML structure itself, not the data it contains.
[xml]$myXML = Get-Content C:\blah\settings.xml
$myXML.settings.ChildNodes.Item(0).value = "New York, USA"
$myXML.Save("C:\blah\settings.xml")
For the Skinsettings example, try something like:
$myXML.settings.skinsettings.setting."#text" = "true"
Check out these resources:
- The Scripting Wife Learns to Use PowerShell to Work with XML
- Use PowerShell to Parse an XML File and Sort the Data
- How to update an Xml Element value using PowerShell