Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell array is not cleared

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

like image 499
ComFreek Avatar asked Nov 08 '12 19:11

ComFreek


People also ask

How to Clear array in PowerShell?

It's not easy to delete array item in PowerShell. Array data structure is not designed to change size. Instead of delete, just replace the value with $null .

How to define an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

What is @() in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

How do I add an item to an array in PowerShell?

To add an item to an array, we can have PowerShell list all items in the array by just typing out its variable, then including + <AnotherItemName> behind it. The + method works, but we have a shorter, more common way to accomplish the same thing.


1 Answers

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:

  1. @() 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.)
  2. 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.)
like image 113
Dan Fitch Avatar answered Oct 06 '22 00:10

Dan Fitch