Welcome to this addition of the PowerShell ABC's where you'll find 26 posts detailing a component of the PowerShell scripting language, one letter at a time. For today's letter of "X", I'll discuss PowerShell's ability to work natively with XML.
XML (Extensible Markup Language) is being used more and more in today's computing environments. PowerShell is no exception in that it uses XML for its type and configuration files as well as for it's help system.
Since PowerShell uses XML so much internally, it makes sense that it has to expose a way to process XML documents in a simple way.
The [xml] Data Type
PowerShell supports XML documents as a primitive data type. This is powerful in that it allows you to access a XML Document just as you would an object with elements and child elements being properties on that object. By using the [xml] type literal you can convert a string containing XML text into a System.XML.XmlDocument object. The following example illustrates creating a XML object and
Since the [xml] type object is a true object, you can do more than look at it. You have the full abilities to add, modify, and remove content with the underlying System.Xml.XmlDocument methods and properties. The following example adds and removes child elements with the AppendChild and RemoveChild XmlDocument methods.
You can load and save XML documents to and from the file system with the Load() and Save() methods in the XmlDocument object. The following illustrates how to save the previously created document and then reload it again into another variable.
There are a couple of Cmdlet's that are specifically designed for the serialization of objects. Serialization is the process of saving and restoring an object or objects to a file or network stream. The Two Cmdlet's are Export-Clixml and Import-Clixml. In the following example, I'll show how to export the contents of an arbitrary object to an XML stream and restore it.
These Cmdlets provide an easy way to save and restore collections of objects but there are some limitations. These Cmdlets can only load and save a fixed number of primitive types. Other types are broken apart, or shredded, into a property bag composed of primitive types. Unfortunately, this means that objects with non-primitive types, cannot be restored to exactly the same type they were originally.
Another issue with serialization is the matter of property depth. An object can have properties, which in turn can have properties, and so on. The chain of properties that have properties is referred to as property depth. Since this could ultimately yield a very large output file for even the simplest of objects, the Export-Cmlxml defaults to a property depth of 2 for exports. You can override this with the -depth parameter if you wish.