Question: I am using the code below:

```
$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

```

I have globally declared `accountArray` variable but when I try to modify that variable in `Function` it only iterates once and loop ends(i.e. it only removes one element), what I am doing wrong?

Answer: 
You cannot change a collection like ArrayList while iterating its items like that.

If all you want to do is empty the list, use `$global:accountArray.Clear()`

If you want to use a loop, do that by using the element index and go from bottom to top:

```
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)
    }
} 

```

Or use the `Remove` method slightly different by letting `$n` not being a member of the list itself, but merely the value it stores:

```
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)
    }
}

```

P.S. the comment character in PowerShell is `#`, not `//`
You can't modify a list you are iterating through. The collection is modified so it's not the same one it started with. You can call ToArray() on the list to fix this.

```bsh
Function Remove-Numbers
{
    foreach ($n in $global:accountArray.ToArray()) {
            $global:accountArray.Remove($n)
    }
}

```