Prof. Powershell

XML Marks the Spot

PowerShell 2 can create viable XML files you can use just about anywhere you want to use an XML file's data.

In PowerShell 1.0 you could use the Export-Clixml cmdlet to create an XML representation of a group of objects. However, these serialized objects and resulting XML file weren't designed to be used anywhere except PowerShell and the Import-Clixml cmdlet. If you wanted to use the XML file somewhere else you were out of luck. To create viable XML file required a bit of manual file creation.

Fortunately PowerShell 2.0 puts that behind with ConvertTo-XML.

Much like ConvertTo-HTML, you can pipe a PowerShell expression to ConvertTo-XML which will create an XML representation of the objects:

PS C:\> get-service | convertto-xml

If you run this command, you don't get a file, you get an XML object. The more correct way to use this cmdlet would be:

PS C:\> $svc=get-service | convertto-xml

If you pipe $svc to Get-Member you'll see that it is in fact an XML object. You can work with $svc as you would any XML object in PowerShell.

$svc.objects.childnodes | foreach {
   $_.property | where {$_.name -match "^Name|Status"}
   | select Name,'#text'
} | Format-Table -autosize

I never said it was easy to work with, and a full discussion of XML objects is beyond the scope of this column. But if you know how to work with XML you can.

More than likely though, you will want to save the XML information to a file. Don't think this is all you need to do:

PS C:\> $svc | out-file services.xml

Instead you need to invoke the Save() method from the XML object:

PS C:\> $svc.Save("c:\files\services.xml")

Now you have an XML file you can use anywhere you wish. Before we wrap up the lesson though, let me give you the syntax to use so you can export and save to XML with a single command:

PS C:\> (get-process | Select Name,*Set,ID,Handles,Path,*time | ConvertTo-xml).Save("c:\files\procdata.xml")

Place the PowerShell code that you want to convert to XML within the parentheses. PowerShell will parse this code and create the XML object internally. Use the Save() method, specifying a name for the final XML file.

Note: This information is based on pre-release software and is subject to change.

About the Author

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.

comments powered by Disqus
Most   Popular

SharePoint Watch

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.