Powershell Change XML file Tutorial

This tutorial focusses on modifying / updating an XML in Powershell command line. We will provide a simple XML to start with and describe how easily you can manipulate them in Powershell, by following some simple commands. You will need Powershell version 2 or higher to run the examples provided in this article. Also, make sure you read our tutorials on reading XML from file and simple XML parsing techniques   to get  a basic understanding on what this series is all about.

Modify XML in Powershell - Input

We will use the following XML as an example to discuss the options:


For this XML, we will explain how to modify the descr value  and cost value. We will also explain if it is possible to perform any arithmetic operations on XML tags using this approach.

Changing XML tag value using Powershell - Example

To change the tag value, follow the command as shown below (Note: We print the command before and after the change to confirm if the update has happened)

PS C:\> $my_xml=[xml] "<item><descr>TV</descr><cost>2500</cost></item>"

PS C:\> $my_xml //Cannot print this way as discussed earlier

format-default : The member "Item" is already present.
    + CategoryInfo          : NotSpecified: (:) [format-default], ExtendedType
    + FullyQualifiedErrorId : AlreadyPresentPSMemberInfoInternalCollectionAdd,

PS C:\> $my_xml.item.descr //print current description
PS C:\> $my_xml.item.cost //print current cost
PS C:\> $my_xml.item.descr="Washer" //update descr to washer
PS C:\> $my_xml.item.descr
PS C:\> $my_xml.item.cost="3000" //update cost to 3000
PS C:\> $my_xml.item.cost
PS C:\> $my_xml.item.cost=3000 //you need to specify the value in quotes
Cannot set "cost" because only strings can be used as values to set XmlNode properties.
At line:1 char:14
+ $my_xml.item. <<<< cost=3000
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

PS C:\>

The examples presented above to update XML nodes are self explanatory. I have added comments where applicable. If you have a question on them, you can post it in the comments section of this blog post.

You can try some arithmetic operations, but as tags are handled as strings, they will get concatenated to the output. Refer below for an example

PS C:\> $my_xml.item.cost.gettype().FullName
System.String //type of the tag
PS C:\> $my_xml.item.cost="3000"
PS C:\> 5 + $my_xml.item.cost
3005 //5 added to cost, converts it to integer
PS C:\>  $my_xml.item.cost
3000 //but does not update the XML
PS C:\> $my_xml.item.cost.gettype().FullName
System.String //Also, does not change the type
PS C:\> $my_xml.item.cost=$my_xml.item.cost +5 //5 added to current cost
PS C:\> $my_xml.item.cost
30005 //does not give 3005 but concatenates the output to 30005
PS C:\>

So, what is the option to do this properly? Stay connected, more tutorials on the way. 

No comments:

Post a Comment