Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A gotcha of using .NET collections (ArrayList, List,..) in PowerShell

Tags:

powershell

I just realized this and I've learned it the hard way, so I want to share. Consider you have the following list of strings:

>$list = New-Object -TypeName System.Collections.Generic.List[string]
>$list.Add("x")
>$list.Add("yy")
>$list.Add("zzz")
>$list
x
yy
zzz

Now if you want to get the number of items in the list, you would access the .Count property, and it gives you "3" as expected.

>$list.Count
3

However, sometimes you would make mistake by accessing .Length instead of .Count. In other languages, like Python or C#, you would get an error saying this property is not available. But in PowerShell, it turns out that, if it's not found on that object, it iterates through the contained objects and access the property on them. So you end up having a list of Lengthes! Surprise!!

>$list.Length
1
2
3

You can even invoke methods!

>$list.ToUpper()
X
YY
ZZZ

Note that, as I've tried, this "feature" also works for System.Collections.ArrayList. But it does not work for PowerShell's builtin array type.

What is this "feature" called? And why is it designed such way? It's very surprising and error-prone.

like image 881
KFL Avatar asked Jun 05 '13 00:06

KFL


People also ask

How do you declare an ArrayList in PowerShell?

What is PowerShell Arraylist. We can use an ArrayList to store a list of items in PowerShell. Unlike array, arraylist's length is not fixed, it can changed. One difference between array and ArrayList is, An array is strongly types, that means array can store only specific type elements.

How do you create a collection in PowerShell?

To create an array of a specific type, use a strongly typed collection: PS > $list = New-Object Collections. Generic. List[Int] PS > $list.

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 you declare a string array in PowerShell?

PowerShell array of strings is the collection of string objects that is multiple strings are residing into the same collection which can be declared using String[], @() or the ArrayList and can be used in various ways like functions, in the file content, as a variable and can perform the multiple operations on the ...


1 Answers

Keith Hill mentioned in the comment that this is a new feature called Member Enumeration in V3.

Refer to "New V3 Language Features" on devblogs.microsoft.com.

like image 109
KFL Avatar answered Sep 30 '22 11:09

KFL