Powershell:对全局 ArrayList 的迭代不符合预期

spo*_*993 1 powershell

我正在使用下面的代码:

$global:accountArray =  New-Object -TypeName "System.Collections.ArrayList"


$global:accountArray.Add("0001")
$global:accountArray.Add("0002")
$global:accountArray.Add("0003")
$global:accountArray.Add("0004")
$global:accountArray.Add("0005")

Function Remove-Numbers
{
    // This loop only iterates one time
    foreach ($n in $global:accountArray) {
            $global:accountArray.Remove($n)
    }
}

Remove-Numbers
Run Code Online (Sandbox Code Playgroud)

我已经全局声明了accountArray变量,但是当我尝试修改该变量时Function,它只迭代一次并循环结束(即它只删除一个元素),我做错了什么?

The*_*heo 5

您不能在像这样迭代其项目时​​更改像 ArrayList 这样的集合。

如果您只想清空列表,请使用 $global:accountArray.Clear()

如果要使用循环,请使用元素索引并从下到上执行此操作:

Function Remove-Numbers {
    # use a loop to remove the items. go from last to first
    for ($i = $global:accountArray.Count -1; $i -ge 0; $i--) {
            $global:accountArray.RemoveAt($i)
    }
} 
Run Code Online (Sandbox Code Playgroud)

或者使用Remove稍微不同的方法,让$n不是列表本身的成员,而只是它存储的值:

Function Remove-Numbers {
    # use a loop to remove the items. Iterate using the value of the item, not the item itself.
    foreach ($n in $global:accountArray.ToArray()) {
        $global:accountArray.Remove($n)
    }
}
Run Code Online (Sandbox Code Playgroud)

PS PowerShell 中的注释字符是#, 不是//