January 18th, 2008

Format-XML

PowerShell Team
PowerShell Team

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

Category
PowerShell

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.