arrays - 为 foreach 循环中的每个循环创建一个新变量

标签 arrays powershell foreach

如何将 $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"
   }

最佳答案

您必须在循环之前的某个位置初始化哈希表:

$myArray = @{} 

并添加

$myArray.Add($count, $org)

到你的foreach循环。

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

关于arrays - 为 foreach 循环中的每个循环创建一个新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6982160/

相关文章:

arrays - Lua/LOVE 索引问题

c - C 中的牌组洗牌可以编译,但会出现段错误

php - 如何在 PHP 中从字符串数组创建对象

c# - 在 Razor 中声明变量

php - 如何在 PHP 中使用 foreach 循环设置多个复选框中的选定属性?

php - 在where子句中使用数组,其中检查字段包含逗号分隔的单词

string - 从全名字符串知道路径是文件夹还是文件?

validation - 通过 ValidateScript 属性将默认参数值与验证相结合

powershell - 如何在调用 Add-PSSnapin 之前检查 PowerShell 管理单元是否已加载

php - PHP语法错误