Adding elements to XML objects with Windows PowerShell

While it’s very easy to load and view the content of XML documents how do you add new elements? Here’s how:

Let’s create a simple XML document, one parent node with two children:

PS> $x = “<top>

<first>first child</first>

<second>second child</second>


PS> $

first                                   second
—–                                   ——
first child                             second child

Add a new element below our top element with textual content:

PS> $e = $x.CreateElement(“third”)
PS> $e.set_InnerText(“third child”)

(Windows PowerShell wraps .Net object properties with method calls. The method set_InnerText actually refers to the .Net property InnerText, and is required because our XML adapter assumes that all properties come from your XML)

PS> $$e)

What does our XML look like now?

PS> $

first                      second                     third
—–                      ——                     —–
first child                second child               third child

That’s it!


Nigel Sharples [MSFT]
Windows PowerShell Team
Microsoft Corporation
This posting is provided “AS IS” with no warranties, and confers no rights.