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
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 .
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 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.
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.
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.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With