PowerShell: How to Update Content in XML File


Often you may want to use PowerShell to update specific content in an XML file.

You can use the following syntax to do so:

[xml]$my_xml = Get-Content my_data.xml

foreach ($element in $my_xml.team.info) {
    $element.loc = "National Basketball Association"
}

$my_xml.Save("my_data.xml")

Here is what this particular example does:

  • First, use a Get-Content cmdlet to retrieve the content from the XML file named my_data.xml.
  • Then, use a foreach cmdlet set the content of each node with the structure team.info.loc to be “National Basketball Association.”
  • Lastly, use the Save command to save these changes to the original XML file.

The following example shows how to use this syntax in practice.

Example: Use PowerShell to Update Content in XML File

Suppose that we have an XML file named my_data.xml in our current directory.

We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to change the text “NBA” to “National Basketball Association” for each node that ends in the <loc> tags.

We can use the following syntax to do so:

[xml]$my_xml = Get-Content my_data.xml

foreach ($element in $my_xml.team.info) {
    $element.loc = "National Basketball Association"
}

$my_xml.Save("my_data.xml")

The following screenshot shows how to use this syntax in practice:

PowerShell update XML file

Notice that each occurrence of the text “NBA” has been replaced with “National Basketball Association” instead.

Feel free to use similar syntax to update any specific content that you would like in your own XML file.

Note: You can find the complete documentation for the foreach statement in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Edit a JSON File
PowerShell: Use ConvertTo-Json on Array with Single Item
PowerShell: How to Loop Through Each Line of CSV File

Leave a Reply