Trinitrotoluene
Trinitrotoluene

Reputation: 1458

Reading multiple variables into an array through a loop

I'm sure this is simple but I am just trying to wrap my head around it. I have an XML file that looks like this:

<software>
    <program>Bob</program>
    <program>Reader</program>
    <program>Hello</program>
    <program>Java</program>
</software>

I am then pulling it into the script like this

[xml]$xml = Get-Content configuration.xml
 foreach( $entry in $xml.software)
{
$arrayofsoftware = $entry.program
}

First thing to note is I don't know how many program entries will be in the XML. What I am looking to do is put all of that software into some sort of array. I then need to seperate it later on into seperate variables (as I need to pass each one as a switch to a command line).

Can anyone throw me in the right direction?

Upvotes: 3

Views: 8040

Answers (1)

Shay Levy
Shay Levy

Reputation: 126902

This will create a collection of program names and assign them to the $arrayofsoftware variable.

[array]$arrayofsoftware = $xml.software.program

To create a separate variable for each value, use the New-Variable cmdlet:

for($i=0; $i -lt $arrayofsoftware.count; $i++)
{
    New-Variable -Name "arrayofsoftware$i" -Value $arrayofsoftware[$i]
}

# get a list of arrayofsoftwar variables
Get-Variable arrayofsoftwar*

Name                           Value                                                                                                                                     
----                           -----                                                                                                                                     
arrayofsoftware                {Bob, Reader, Hello, Java}                                                                                                                
arrayofsoftware0               Bob                                                                                                                                       
arrayofsoftware1               Reader                                                                                                                                    
arrayofsoftware2               Hello                                                                                                                                     
arrayofsoftware3               Java      

Upvotes: 3

Related Questions