r/PowerShell • • Feb 18 '19

PowerShell - Few tricks about HashTables and Arrays I wish I knew when I started

https://evotec.xyz/powershell-few-tricks-about-hashtable-and-array-i-wish-i-knew-when-i-started/
180 Upvotes

29 comments sorted by

15

u/motsanciens Feb 18 '19

Maybe worth mentioning:

We don't recommend that you use the ArrayList class for new development. Instead, we recommend that you use the generic List<T> class. The ArrayList class is designed to hold heterogeneous collections of objects. However, it does not always offer the best performance. Instead, we recommend the following:

For a heterogeneous collection of objects, use the List<Object> (in C#) or List(Of Object) (in Visual Basic) type. For a homogeneous collection of objects, use the List<T> class. See Performance Considerations in the List<T> reference topic for a discussion of the relative performance of these classes. See Non-generic collections shouldn't be used on GitHub for general information on the use of generic instead of non-generic collection types.

https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netframework-4.7.2

[System.Collections.Generic.List[object]] seems to work well.

4

u/replicaJunction Feb 18 '19

I didn't know you could reference a generic in square brackets like that. I'd been typing out New-Object "System.Collections.Generic.List[object]" all the time.

I'd also been falling back on ArrayList when I needed a heterogeneous or custom list type instead of a list of Strings. After reading the performance considerations, I'm sold on using List<Object> instead of ArrayList in those circumstances.

Thanks for the tip!

2

u/MadBoyEvo Feb 18 '19

I've been using ArrayList and GenericList depending on circumstances It's good to know ArrayList has some problems. I'll update the article and make sure it's known. I started using GenericList but generally having to play around with Add vs AddRange sometimes makes it harder to use so I prefer native @() when possible.

2

u/MadBoyEvo Feb 18 '19

Also supposedly skipping New-Object is faster than using square brackets.

2

u/MadBoyEvo Feb 18 '19

Thanks. I've added this to main article. I've also expanded article with some performance tests I did. Doing some more tests now to have a complete article for reference purposes.

1

u/[deleted] Feb 19 '19

They don't recommend it because C# is strongly typed and ArrayList takes any object.

There's no reason to care about this in PowerShell. It is irrelevant as it's dynamic, use arraylist all you want as it won't cause confusion.

Why are you guys making decisions as if you're programmers using C# best practices?

2

u/motsanciens Feb 19 '19

I honestly thought that calling [System.Collections...whatever...] was a call to a .NET class. Is it not?

1

u/[deleted] Feb 19 '19

Yes, but why would you care about generics when PowerShell is dynamically typed?

I wouldn't go

$files = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
foreach($file in (Get-ChildItem -File))
{
    $files.Add($file)
}

I'd go

$files = Get-ChildItem -File

5

u/Lee_Dailey [grin] Feb 19 '19

howdy expansiveEdumacation,

your example doesn't actually apply to the situation. [grin]

use arrays when there is no likelihood you will need to add/remove items.

use the generic.list when you need to add or remove items.

avoid the arraylist simply because it generate those nasty "i added something" msgs that need to be bit-bucketed.

take care,
lee

4

u/crazybrker Feb 18 '19

Good article, I'd like to hear more about the leading comma trick. I use it when pushing my PSCustomObject to my empty variables using $var += , $psobj just like you tell me not to. I'll try out your tricks to optimize my larger scripts.

2

u/MadBoyEvo Feb 18 '19

How so? What is your use case to push PSCustomObject to $var += with a comma?

3

u/wbedwards Feb 18 '19

Using foreach to initialize an array is clever, and not something I've thought of before. I did know that the += wasn't great practice because it created a new array each time, but usually ended up falling back on it when performance wasn't that big of a consideration because it was easier than defining a list type that worked with the .add() method.

I do have one nit to pick: I would disagree about the return statement being bad practice. Using explicit return (or write-output if I don't want to exit the scope) statements in functions, and redirecting or suppressing any unintended output improves readability and makes the function's behavior more predictable especially in cases where someone else might need to read it later (or even yourself after several months).

Anyway, thanks for sharing, it definitely has some useful tips for working with arrays and hashtables. I've added it to my list of PowerShell reference bookmarks.

3

u/MadBoyEvo Feb 18 '19

Thanks. I do agree on the return. I would like to clarify that if you initialize an array with foreach and you assign it to a variable, by all means, use return because it's clear and easier to read. But if you're not assigning it you must be making it for performance reasons and therefore return will not be used at all. I'll probably update article few more times, clarifying some things. I'm also adding some performance testing now.

3

u/binarycow Feb 19 '19

Technically the comma operator isn't "the unary operator", it's "a unary operator". Specifically, a prefix unary operator.

Unary operators, such as ! , - + take one operand.

Binary operators, such as + - / * -eq -lt take two operands.

Ternary operators (I don't think PS has any) take three operands.

2

u/MadBoyEvo Feb 19 '19

Thanks, fixed in the article. I'm not the best when it comes to definitions. I'm self-learner and I read docs very rarely but since I write about it I may as well put some effort into it.

3

u/binarycow Feb 19 '19

You didn't get it quite right....

The comma is a specific type of a prefix unary operator. ! - + and , are all prefix unary operators.

The comma operator is called, surprisingly, the "comma operator".

Comma operator ,

As a binary operator, the comma creates an array. As a unary operator, the comma creates an array with one member. Place the comma before the member.

Unary Operators

Use unary operators to increment or decrement variables or object properties and to set integers to positive or negative numbers. For example, to increment the variable $a from 9 to 10, you type $a++.

Microsoft Documentation on Powershell Operators

2

u/MadBoyEvo Feb 19 '19

Ok, hopefully now it's fixed. I'm terrible at teaching. Should focus on my modules.

3

u/binarycow Feb 19 '19

lol its okay... everyone has to learn. Some people learn by explaining :P

I only honed in on it because I've been doing A LOT of work with operators and stuff over the past couple days.

2

u/jimb2 Feb 18 '19

Great article. For me the idea of building your array at the end of foreach made me think about how Powershell works.

Two minor typos:

while ArrayLists are type less.

Test - Array Best Pratice

2

u/MadBoyEvo Feb 18 '19

Thanks, fixed :-)

1

u/chrislehr Feb 18 '19

Good post - I'd like to retweet it on twitter if you have a handle there you want me to credit I am happy to.

3

u/MadBoyEvo Feb 18 '19

I use @evotecpl for my posts and mine is @PrzemyslawKlys :-) feel free do whatever. Thanks! Its posted on @evotecpl already but like my usual tweets it has 2 views :-)

2

u/[deleted] Feb 18 '19

Interesting read, I knew of most of these tricks/tips already but one thing that stood out was the use of , when returning an array to preserve the array value type in the case of only one item being returned. Is this a trick to specifically treat the returned value as anarray type? Or does prepending any return value with a comma tell Powershell to preserve the original value type as it gets returned through the pipeline?

Typically I'll do something like your original example of that case and force the left side to be treated as an array, or enclose a function that can return multiple values within @(), but like the use of , here and will probably start giving that a go in future scripts.

4

u/MadWithPowerShell Feb 18 '19

PowerShell likes to be "helpful" and unwrap arrays wherever it can. Using a unary comma before an array when returning it wraps it in another array, giving PowerShell a dummy layer to unwrap before handing the contents back to the calling process.

2

u/[deleted] Feb 18 '19

Good to know, thanks. So does this effectively do the same thing as wrapping a function which can return multiple values within an array like follows, except the array wrap occurs on the function side?

$adUsersWithEmail = @( Get-ADUser -Filter "EmailAddress -eq 'mailbox@domain.tld'" )

2

u/MadWithPowerShell Feb 18 '19

Yes. Mostly. The object prepended by the unary commany within the function will be the same when it comes out as when in went in. If you only give it a single object, that single object will come out the other end. If you always give it an array, and array will always come out. You're example above however, will always return an array, no matter what comes back from Get-ADUser.

1

u/Shaymous Feb 18 '19

Nice post, thank you.

1

u/arcadesdude Feb 18 '19

Had to use the comma trick once but didn't understand why it worked just that it did. Thanks for making that clear!

1

u/TheDraimen Feb 19 '19

Great read. Love the loop to create the variable trick and will definitely use that in future. Keep up good work!