Monday, 3 May 2021

Write XML Files with Powershell - The Easy Way

 I needed to create a custom XML file using powershell as part of a script I was developing. I found it difficult to understand and use the in-built XML functionality with powershell so I attempted to simply use write-output commands to write the XML file. It worked - mostly, but the application I was submitting the XML file wasn't recognizing it. As it turns out there's some hidden properties within a properly formed XML file which requires a little trick to get right when forming it this way - so here's how I did it..

            $xmlfile = "C:\temp\test.xml"
            write-output '<?xml version="1.0"?>' | out-file "$xmlfile"
            write-output '<test>' | out-file "$xmlfile" -append
            write-output "  <version>1.0</version>" | out-file "$xmlfile" -append
            write-output '</test>' | out-file "$xmlfile" -append

            $xml = [xml](Get-Content $xmlfile)
            $xml.Save($xmlfile)

The first part of the script is fairly straightforward - declare the path to your XML file in the $xmlfile variable.

Then, use write-output commands to enter the text data into your XML file - make sure you include the -append argument after the first line to ensure the lines are appended onto the end of the file - you can open the file in a text editor such as NotePad++ to make sure it appears as you expect. Make sure you close off all your tags so that formatting is valid.

The last 2 lines is the trick I previously mentioned - use the [xml] class with get-content to import the XML file into the $xml variable. Once the data is in the $xml variable, it is then re-saved - these 2 lines are what puts the hidden formatting into the XML file to make it valid.


No comments:

Post a Comment