Powershell can slice and dice arrays all day long, and we use them all the time. However, when we are testing stuff and creating dummy arrays the syntax can be a bit awkward. Its quite straightforward and understandable, but its just a pain to type
For example
1: PS 39 > $i = "one","two","three"
2: PS 40 > $i
3: one
4: two
5: three
Now for me that is just way too many quotes and commas. This can easily be addressed with a new function called New-Array. Are we going to have to parse and add quotes and do all kinds of crazy stuff to get this working ? Not really. Here’s the function and how to use it.
1: PS 41 > function new-array {$args}
2: PS 42 > $i = new-array one two three four five six
3: PS 43 > $i
4: one
5: two
6: three
7: four
8: five
9: six
Ah, now that is much better. All this does is return the $args array which is an array that you get in every function be default. $args[0] is the first argument. $args[1] is the second etc etc.
That being said we are not quite there. Lets say you want to be really sure you create an Array. In the case where you originally have only 1 $arg it will return a scalar. Let me demonstrate.
1: PS 58 > function new-array {$args}
2: PS 59 > $i = new-array 1
3: PS 60 > $i += 2
4: PS 61 > $i
5: 3
In this case, $i ends up being a scalar with a value of 1 and then when you add 2 to it, you get $i = 3.
What we want is to be able to use the += operator to add a value to the array. There are multiple ways to force a scalar to be an array when you declare it but i think the comma operator is the shortest. So we make one quick addition to our new-array function.
1: PS 62 > function new-array {,$args}
2: PS 63 > $i = new-array 1
3: PS 64 > $i +=2
4: PS 65 > $i
5: 1
6: 2
Pretty cool!
February 12, 2008 at 5:00 pm
[...] Powershell function New-Array [...]