Powershell array is not cleared

arrays, powershell

Solution

Powershell does some array-casting trickery when you do `+=`, so the easy solution is to do `$arr.Add("z")`. Then `$arr.Clear()` will act like you expect.

To clarify:

- `@()` is a Powershell array. It uses `+=`, but you can't `Clear` it. (You can, however, do `$arr = @()` again to reset it to an empty array.)

- `ArrayList` is the .NET collection. It uses `.Add`, and you can `Clear` it, but for some reason if you `+=` it, Powershell does some weird array coercion. (If any experts care to comment on this, awesome.)

Problem

My source code: ``` # $arr = @(); results in same behaviour $arr = New-Object System.Collections.ArrayList; $arr.Count; $arr += "z"; $arr.Count; $arr.Clear(); $arr.Count; ``` Output: 0 1 1

Original source