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:
A few lines to update the firstName value:
Now add in another record to the original file:
Run the same command again:
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:
, we get this…
We can do the update in 1 line…
, and now the file is updated OK:
Adding new elements with attributes
Using the state just now of the file as our starting point…
, this will only create a new record if that id (103) does not already exist…
, giving this on the next execution, and all executions after that (i.e. the Rebecca rows):