【问题标题】:create a new variable for each loop in a foreach-loop为 foreach 循环中的每个循环创建一个新变量
【发布时间】:2011-10-22 08:50:24
【问题描述】:

如何将 $org 与 $count 一起放入数组中?

像这个示例数组:

$myArray = @{
  1="SampleOrg";
  2="AnotherSampleOrg"
}

另一个例子:

$myArray = @{
  $count="$org";
  $count="$org"
}

foreach 示例:

$count=0;get-organization | foreach {$count++; $org = $_.Name.ToString();write-host $count  -nonewline;write-host " $org"}
$answer = read-host "Select 1-$count"

上面会显示:

1 SampleOrg
2 AnotherSampleOrg

Select 1-2:

之后我想做的就是把数组放在一个开关中使用。

例子:

switch ($answer)
   {
     1 {$org=myArray[1]} #<-- or whatever that corresponds to "SampleOrg"
     2 {$org=myArray[2]} #<-- or whatever that corresponds to "AnotherSampleOrg"
   }

【问题讨论】:

  • 我不确定我是否理解正确,但 IMO 你只需要在你的foreach-loop 中添加一个$myArray.Add($count, $org)。编辑:你必须在循环之前的某个地方初始化你的数组:$myArray = @{}
  • 您的解决方案非常有效! $myArray = @{};$count=0;get-organization | foreach {$count++; $org = $_.Name.ToString();write-host $count -nonewline;write-host " $org";$myArray.Add($count, $org)}

标签: arrays powershell foreach


【解决方案1】:

你必须在循环之前的某个地方初始化你的哈希表:

$myArray = @{} 

并添加一个

$myArray.Add($count, $org)

到你的 foreach 循环。

编辑:有关 hastable/array 的讨论请参阅整个线程;)我只是保留了原始帖子中的变量名称

【讨论】:

  • 最终结果:$myArray = @{};$count=0;get-organization | foreach {$count++; $org = $_.Name.ToString();write-host $count -nonewline;write-host " $org";$myArray.Add($count, $org)}
  • $myArray = @{} 不是数组
  • 哈希表是一种数组。 (关联数组)
  • 哈希表是一种集合,但不是一种数组。
【解决方案2】:

看起来您混淆了数组和哈希表。数组是有序的,并由数值索引。哈希表是关联的,并且由任何定义了相等性的值索引。

这是数组语法

$arr = @(1,2,3)

这是哈希表语法

$ht = @{red=1;blue=2;}

对于您的问题,以下将起作用

$orgs = @(get-organization | % { $_.Name })

这将创建一个基于 0 的数组,映射 int -> OrgName,所以

$orgs[$answer]

将获得正确的名称。或者,如果您使用的是基于 1 的索引

$orgs[$answer-1]

注意,我移除了开关,因为没有理由这样做。

【讨论】:

  • 这不是用嵌套的哈希表创建一个数组,而不是相反吗?
  • @JNK - 是的,完全正确。由于索引似乎是一个整数,因此数组是最合适的数据结构
  • 明白了。 $answer 索引让我失望 - $answer 是 int 而不是键!看起来他也想使用基于 1 的索引,所以他应该注意 0。
  • 在发布的解决方案中没有前缀编号,即 1 SampleOrg 另外,当我得到 $orgs[1] 的值时,我得到的是名称和值,而不是单个变量。
  • 如果 $answer=1 对应于 AnotherSampleOrg 那么在 switch case: 1 {$org=orgs[$answer]} 这将 $orgs 设置为: Name Value ---- -- --- SampleOrg AnotherSampleOrg 但我只想设置为 AnotherSampleOrg。
猜你喜欢
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 2021-12-02
  • 2014-08-03
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
相关资源
最近更新 更多