PowerShell,如何增加变量名? [英] PowerShell, how do I increment variable names?

查看:32
本文介绍了PowerShell,如何增加变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个解析 XML 文件的 PowerShell 脚本,并将一些解析的值保存为变量以备后用.

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

例如,假设我的 XML 如下所示,

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

截至目前,这部分有效,但是,因为我想从每个单独的 foo 中提取 id 号或 qux 字符串,我想做类似于以下的操作(伪代码):

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
}

我意识到这可能没有任何意义,或者我可能不清楚,但我需要一些帮助.本质上,有没有办法增加一个变量,使它的名称可以是,例如,$foo1、$foo2、$foo3 等,而不改变它的值?本质上,

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

推荐答案

使用 新变量 cmdlet.

Use the New-Variable cmdlet.

例如

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

应该给你

Hello, World!

这篇关于PowerShell,如何增加变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆