Change Element in XML using PowerShell
In this blog post, we will explore a PowerShell script that helps change elements within an XML file. This script is designed to update specific nodes and their corresponding child elements in an XML dataset.
Prerequisites
The Script
This script uses a combination of built-in PowerShell commands and XML manipulation techniques to achieve its goal.
Clear-Host
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$file = "$dir\myXML.xml"
$newfile = "$dir\myXML-new.xml"
#read in the json
[xml]$xml = get-content -Path $file
How It Works
Reading the XML File
The script starts by clearing the console and retrieving the path of the current PowerShell script using `$MyInvocation.MyCommand.Path`. It then uses `Split-Path` to get the directory path where the script is located. The script also defines two file paths: `$file` for the original XML file and `$newfile` for the modified XML file.
foreach ($element in $xml.NewDataSet)
{
$element.myelement = "xxxxxxxxxxx"
}
Updating Node Elements
The script then loops through each element in the `NewDataSet` node using a `foreach` loop. For each element, it updates the `myelement` property with a new value.
foreach ($element in $xml.NewDataSet.mysubnode)
{
$element.element1 = "xxxxxxxxxxx"
$element.element2 = "xxxxxxxxxxx"
$element.element3 = "xxxxxxxxxxx"
}
Updating Sub-Node Elements
The script then loops through each element in the `mysubnode` node using another `foreach` loop. For each element, it updates three child elements (`element1`, `element2`, and `element3`) with new values.
# Then you can save that back to the xml file
$xml.Save($newfile)
Key Code Snippets
The following code snippets demonstrate how the script manipulates and updates elements within the XML file:
[xml]$xml = get-content -Path $file
foreach ($element in $xml.NewDataSet)
{
$element.myelement = "xxxxxxxxxxx"
}
foreach ($element in $xml.NewDataSet.mysubnode)
{
$element.element1 = "xxxxxxxxxxx"
$element.element2 = "xxxxxxxxxxx"
$element.element3 = "xxxxxxxxxxx"
}
$xml.Save($newfile)
Usage Examples
This script can be used to update specific elements in an XML file. For example, if you have an XML file containing a dataset with nodes and child elements, you can use this script to modify those elements.
Conclusion
In conclusion, this PowerShell script demonstrates how to read and manipulate XML files using the `Get-Content` cmdlet and XML manipulation techniques. This script can be used as a starting point for more complex XML processing tasks in PowerShell.