PowerShell: XML editing continued

This shows that in editing XML in PowerShell, if you assume that there is a single instance of an element, and there is more, then you get a very misleading error.

Simple piece of XML:

PSXml01

A few lines to update the firstName value:

PSXml02

All fine:

PSXml03

Now add in another record to the original file:

PSXml04

Run the same command again:

PSXml02

This time…

PSXml05

Actually as the contrast is poor, this is the error:

The property ‘firstName’ cannot be found on this object. Verify that the property exists and can be set.
At line:3 char:1
+ $xml.students.student.firstName = “Harry”
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException

The claim that ‘firstName’ might not exist is clearly wrong, but it is our/my own fault for being sloppy.

If we are now more precise about the record we are looking for:

PSXml06

, we get this…

PSXml07

We can do the update in 1 line…

PSXml08

, and now the file is updated OK:

PSXml09

Pastebin here here

Adding new elements with attributes

Using the state just now of the file as our starting point…

PSXml09

, this will only create a new record if that id (103) does not already exist…

PSXml10

pastebin

, giving this on the next execution, and all executions after that (i.e. the Rebecca rows):

PSXml11

pastebin

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s