XML Marks the Spot Part 2: Capturing Serialized Data
Part 2 shows how to convert and retrieve XML data without losing the hierarchical format.
- By Jeffery Hicks
In the previous lesson I demonstrated how to use ConvertTo-XML to turn PowerShell data into a basic XML file. This XML file could be used outside of PowerShell. However, if you were trying out some of my examples, you probably realized a shortcoming (unless you read the help file for the cmdlet). The whole point of XML is to serialize data in a hierarchical fashion. If the object has a property that is a nested object, I need to be able to capture that as well.
By default, ConvertTo-XML only serializes one level deep. But you can adjust this. I'm going to recreate my XML files using a greater depth. Again, I'll use my one-liner shortcut.
PS C:\> (Get-CimInstance win32_service | convertto-xml –depth 3).Save("c:\work\mysvc2.xml")
PS C:\> (Get-CimInstance win32_operatingsystem | convertto-xml –depth 3).Save("c:\work\myos2.xml")
The greater the depth, the larger the file you will end up with.
PS C:\> dir c:\work\mysvc*.xml, c:\work\myos*.xml
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/16/2013 8:13 AM 494180 mysvc.xml
-a--- 7/16/2013 9:51 AM 963848 mysvc2.xml
-a--- 7/16/2013 8:10 AM 5604 myos.xml
-a--- 7/16/2013 9:51 AM 8162 myos2.xml
You need to have some idea of what your data or objects will look like to know how deep you need to capture. You might also need to consider how you intend to use the data once converted to XML. This fact my also determine if you want to include any type information.
With type information (the default), you get XML like figure 1 where I've highlighted the type information.
If you only want the "raw" data, you can eliminate this information.
PS C:\> (Get-CimInstance win32_operatingsystem | convertto-xml –depth 3 -NoTypeInformation).Save("c:\work\myos3.xml")
The XML data is the same except for the additional type attributes.
Again, whether you decide to include type information depends on your plans. Personally, I like having it, especially if I think I might use the XML file in PowerShell again. And that is something we'll look at next time.
Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.