Add XML comment via Powershell

6. June 2011

Just a quick post regarding adding comments to XML files in powershell. ie. Build versions in config files etc.

 

 

param([string]$configfile="C:\Users\mh0030\Documents\PowerShell\CommentTestFile.xml", [string]$comment="My default comment")

$doc = [xml](get-content $configfile)

$root = $doc.SelectSingleNode("/MyRoot")
$comment = $doc.CreateComment($comment)
$doc.InsertBefore($comment,$root)
$outFile = (Split-Path -Parent $configfile) + "\outfile.xml"

$doc.save($outFile)


The two important parts are; the navigator element, in this case $root as selected by "/MyRoot" and the other part is how you want to insert the comment. InsertAfter, InsertBefore, AppendChild.
See the .net documentation for further details here : http://msdn.microsoft.com/en-us/library/system.xml.xmldocument_methods.aspx

 


Michael Høtoft  

Sharepoint Server ,

Comments are closed