Welcome to MSDN Blogs Sign in | Join | Help

Format-XML

Have you ever had an XML file that looks like crap?

The problem is that XML is sorta the data encoding equivalent of Shimmer - sometimes its an encoding for programs and sometimes its an encoding for users.

Our PowerShell MVP Brandon Shell pointed out that the output of Export-CLIXML looked like cra....  errrrrr .... well let's just say that was "programmer oriented".  :-) 

Its true, we were thinking about programs consuming our XML not users.  You'll find lots of XML like that in the world (one reason is that it saves a ton of space by eliminating whitespaces).

So if you ever have a file like that and want to be able to read it, you'll want FORMAT-XML:

function Format-XML ([xml]$xml, $indent=2)
{
    $StringWriter = New-Object System.IO.StringWriter
    $XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter
    $xmlWriter.Formatting = "indented"
    $xmlWriter.Indentation = $Indent
    $xml.WriteContentTo($XmlWriter)
    $XmlWriter.Flush()
    $StringWriter.Flush()
    Write-Output $StringWriter.ToString()
}

Use it like this:

PS> Format-XML ([xml](cat c:\ps\r_and_j.xml)) -indent 4

Enjoy!

 UPDATE: 

Lee Holmes points out that page 153 of his CookBook has an even simpler example:

gps powershell | Export-CliXml c:\temp\powershell.xml

$xml = [xml] (gc c:\temp\powershell.xml)

$xml.Save([Console]::Out)

Nicely done Lee!

Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Published Friday, January 18, 2008 4:27 PM by PowerShellTeam

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# BS on PoSH - Blog » Format-XML (Journey to Pretty XML output)

# re: Format-XML

May I sugget making it a filter?

Friday, January 18, 2008 5:02 PM by jaybaz_MS

# re: Format-XML

There's also a cmdlet for Format-XML in the PowerShell Community eXtensions snapin ... has a few additional options, too.

http://www.codeplex.com/PowerShellCX/SourceControl/FileView.aspx?itemId=101868&changeSetId=29385

Sunday, January 20, 2008 6:50 PM by Joel "Jaykul" Bennett

# re: Format-XML

you can also display xml in a readable format such as this...

$recoveruser = import-clixml \$name.xml

$recoveruser | Sort-Object

Monday, July 06, 2009 2:28 PM by someone

# re: Format-XML

Hello Jeffrey,

It doesn't seem like your example #1 actually uses the passed-in $xml param?

Also, in Lee's example how can I capture it to a string instead of writing it directly to a console?

Thanks,

Dmitry Kalashnikov

Wednesday, September 09, 2009 7:59 PM by Dmitry Kalashnikov

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker