Reputation: 23
I've figured out how to import an xml file into a Powershell variable using the [xml]
tag before the variable and Get-Content
, but filling every variable in Powershell from that new xml-formatted variable one at a time is painstaking.
$variable = $xml.vars.Linux.variable1
$variable2 = $xml.vars.Linux.variable2
... and so on.
Is there a shorter/faster way to just import that xml file and set Powershell variables that match the Node names and fill those variables with the associated Node values? So I don't have to specifically fill every Powershell value with it's corresponding named xml Node, I can just use the Powershell variables without lines of code filling them?
I suspect I may need a loop of some sort...current xml structure is 3 layers with category name for second layer Node and then variable names for Nodes within. For example:
<vars>
<Windows>
<Hostname>Contoso</Hostname>
<IP_Address>192.168.1.1</IP_Address>
</Windows>
<Linux>
<variable1>Yup</variable1>
<variable2>Yessir</variable2>
</Linux>
</vars>
Thanks!
Upvotes: 2
Views: 2378
Reputation: 29450
You can create a variable for each element under a particular node like this:
$xml.vars.Linux.ChildNodes | %{ New-Variable -Name $_.Name -Value $_.InnerText -PassThru}
You can remove the -PassThru
switch to avoid outputting the variables onto the pipeline.
Upvotes: 2
Reputation: 1465
You can access xml nodes really easily in Powershell using xpath. Example:
$myNode = $xmlDoc.SelectSingleNode("//Linux")
From there you can append additional elements on to the node.
First create a new Element
$child = $xmlDoc.CreateElement("NewElementName")
Second add the value to the new child Element
$Child.InnerXML = "ValueHere"
Then Append the child element to the node you have selected
$myNode.AppendChild($child)
This can easily be done in a loop and you'll be working directly with the xml object instead of converting it.
Upvotes: 1
Reputation: 159
Is the goal to turn the xml data into powershell objects you can call elsewhere? Would something like this work for you?
foreach ($var in $variable.linux){
$properties = @{'variable1'=$var.variable1
'variable2'=$var.variable2}
$obj = New-Object -TypeName PSObject -Property $properties -ErrorAction Stop
Write-Output $obj}
Upvotes: 1