PowerShell: Write stuff to an XML file


Needed to recursively list all the files of a certain type and save them as an XML file. Turns out this was pretty easy using PowerShell.

# Make a regular .Net XmlTextWriter
$output = "processes.xml";
$xml = New-Object System.Xml.XmlTextWriter($output, $Null);
$xml.Formatting = "Indented"
$xml.IndentChar = " ";
$xml.Indentation = "1";

# Start writing

# Do the listing and keep outputting XML
Get-ChildItem .. -Recurse -include *.esbp |
foreach {
    $name = $_.BaseName;
    $path = Resolve-Path $_ -relative;

    $xml.WriteAttributeString("id", $name);

# Close the writer, which also closes the root element and document for us

Easy peasy!