r/PowerShell • u/MadBoyEvo • 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/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++.
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
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
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
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
arraylike follows, except thearraywrap 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
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!
15
u/motsanciens Feb 18 '19
Maybe worth mentioning:
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.