Author Posts

May 30, 2017 at 12:19 pm

Hi,
I have defined some XML Text and cast it as XML type. I also have a variable that has some objects in this case VMWare Datacentres using PowerCLI... i would like to add elements based on the number of objects.

Snippet of Code is below:

[xml]$xmlDoc = New-Object system.Xml.XmlDocument
$xmlDoc.LoadXml("")


$datacenters = Get-Datacenter

#
foreach ($datacenter in $datacenters)
{
	$datacentername = $datacenter.name
	#region datacenter loop
	$datacentreelement = $xmlDoc.CreateElement("computer")
    
        $node =$xmlDoc.Audithardware.OU.AppendChild($datacenterelement)
	
	$node.setattribute("Vrt", "Data Center")
	$node.setattribute("Name", "$datacentername")
	#endregion
}

//Apologies some text is in the XML string
I thought by doing it this way I would be able to constantly add on an element to that node in the XML. However when I try to do this in the loop I get an error message

Exception calling "AppendChild" with "1" argument(s): "The node to be inserted is from a different document context."
At line:7 char:5
+     $node =$xmlDoc.Audithardware.OU.AppendChild($datacenterelement)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I have debugged it and it seems that it is failing on this line;

$node =$xmlDoc.Audithardware.OU.AppendChild($datacenterelement). Does any one know of a way to iterate through a loop (in this case datacenters) so that I can add a new element to the node? I would also like to add attributes to it but I want to try doing that myself.

I would be grateful for any direction. I have been reading posts online but they dont talk about this particular circumstance.

May 30, 2017 at 1:44 pm

seens you incorrectly show your context.
$xmlDoc.LoadXml("")

if you have xml inside, use gist
minimal example works ok

PS C:\> [xml]$xmlDoc = New-Object system.Xml.XmlDocument
>> $xmlDoc.LoadXml("[root][node]text[/node][/root]") # brackets changed
PS C:\> 1..2 | foreach { $e = $xmlDoc.CreateElement('computer'); $xmlDoc.root.AppendChild($e) | Out-Null }
PS C:\> $xmlDoc.root

node computer
---- --------
text {, }

June 2, 2017 at 8:13 am

Thanks for the help , I found out the reason why it wasn't working I was passing it the wrong variable. It worked. Thank you.