[Solved] PowerShell, how do I increment variable names?

I am currently writing a PowerShell script that parses an XML file, and it saves some parsed values as variables for use later.

For example, say my XML looks like this,

<head>
  <foo>
   <bar id="1" status="dead">
      <baz>
        <qux>Hello World 001</qux>
      </baz>
    </bar>
   <bar>
      <baz>
        <qux>Hello World 002</qux>
       </baz>
   </bar>
  </foo>

  <foo>
   <bar id="2" status="dead">
      <baz>
        <qux>Goodbye World 001</qux>
      </baz>
    </bar>
   <bar>
      <baz>
        <qux>Goodbye World 002</qux>
       </baz>
   </bar>
  </foo>
</head>

Currently, my script looks like this,

[xml]$report = Get-Content ./helloworld.xml
$foo_sub_length = $report.head.foo.length - 1
$bar_sub_length = $report.head.foo[$foo_sub_length].bar.length - 1
$foo_looper = 0
$bar_looper = 0

As of right now, this part works, however, because I would like to pull the id number, or the qux string from each individual foo, I would like to do something similar to the following (pseudocode):

do {
    do {
      $foo($foo_looper)_id = $report.head.foo[$foo_looper].bar[$bar_looper].baz.id
        $foo($foo_looper)_bar($bar_looper)_qux = $report.head.foo[$foo_looper].bar[$bar_looper].baz.qux
      $bar_looper = $bar_looper + 1
    while $bar_looper <= $bar_sub_length
     }
  $foo_looper = $foo_looper + 1
while $foo_looper <= $foo_sub_length
}

I realize this may not have made any sense, or that I may not have been clear, but I would like some assistance. Essentially, is there a way to increment a variable so that it’s name could be, for example, $foo1, $foo2, $foo3, etc, without changing it’s value? Essentially,

> $bar = 1
> $foo($bar) = hello
> $bar + 1
> $foo($bar) = world
> $foo(1)
hello
> $foo(2)
world
Enquirer: Ondaje

||

Solution #1:

Use the New-Variable cmdlet.

E.g.

$bar = 1
New-Variable "foo$bar" "Hello,"
$bar = $bar + 1
New-Variable "foo$bar" "World!"
"$foo1 $foo2"

Should give you

Hello, World!
Respondent: fsimonazzi

Solution #2:

You want to rename a variable? Variables are exposed as a provider, via the variable: drive. As a result, you can use rename-item on variables, just like files.

ps> rename-item variable:var1 var2
Respondent: x0n

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.