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