How to Export PowerShell Data to XML
I saw a question on StackOverflow the other day asking how to save PowerShell results as XML. If you are lucky, this could be as simple as using the export-clixml cmdlet.
But what if you are doing something more complex where you are pulling data from multiple sources or you want to control every aspect of the structure of the XML you are creating. In that case, I think you have 2 options.
The simplest way would be to build up a string as your xml -
$procs = get-Process
$xml = "<xml>`r`n"
foreach($proc in $procs)
{
$xml += "<process name='" + $proc.Name + "' id='Proc_"+$proc.Id+"'>`r`n"
$xml += "<modules>`r`n"
foreach($module in $proc.Modules)
{
$xml += "<module>"
$xml += $module.ModuleName
$xml += "</module>`r`n"
}
$xml += "</modules>`r`n"
$xml += "</process>`r`n"
}
$xml += "</xml>`r`n"
$xml | out-File -FilePath c:\temp\proc1.xml
The downside of this approach is that you need to build in you are reinventing the wheel and will therefore be responsible for any error checking and insuring that your final document is well formatted XML.
In many cases, a better way would be to build up your output as psobject/arrays/hashtables/etc. You can then use the PowerShell cmdlets for additional massaging if necessary and use the export-clixml to output it as XML. That would look something like this -
$procs = get-Process
$processObject = @()
foreach($proc in $procs)
{
$procInfo = new-Object PSObject
$procInfo | add-Member NoteProperty -Name "Process" $proc.Name
$procInfo | add-Member NoteProperty -Name "ID" $proc.Id
$moduleInfo = @()
foreach($module in $proc.Modules)
{
$moduleInfo += $module.ModuleName
}
$procInfo | add-Member NoteProperty -Name "Module" $moduleInfo
$processObject += $procInfo
}
$processObject | export-Clixml c:\temp\procs.xml
6 months ago - link

