【发布时间】: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