Seems like such a simple topic, yet I have to confess Arrays are driving me crazy in PowerShell. Maybe it’s because I’m used to my old DOS/BASIC habits where DIM Array built a discreet “grid” like an excel sheet … but for whatever reason I find nothing more difficult than actually gathering data I’ve queried into a nice manner… which seems backwards.
Because really that’s all I want 90% of the time: I get how to query and grab the data … let me put it in a nice table so I can run some export-csv or convertto-html on it later.
What’s confusing me is the subtle differences between hashtables, arrays, and all their variations that seems poorly documented and rather just assumed (yeah, three Don Jones books later and I still mentally don’t grasp what’s going on) .
If I read blogs like http://blogs.technet.com/b/heyscriptingguy/archive/2011/12/05/learn-simple-ways-to-handle-windows-powershell-arrays.aspx, then an Array is rather flat. It’s just a bunch of elements, and each element has but a single value. Now lots of people talk about imbedding arrays, or how I can make an array of hashtables, and for the most part I get that, and it’s functional. SO for example I play this game often:
This is pretty neat as the new $array basically behaves as expected: I can call individual elements and their values like $array.Attribute and get what I’m expecting. It formats like garbage though … and isn’t exactly friendly to things like export-csv.
But then I do something seemingly simple and something magical happens:
$array = import-csv “.\somefile.csv”
Wait, wtf? why is it when I look at this array I see multiple values, like columns in a table? And this one is easily converted by things like exportto-csv?! Why does every article I read on arrays say there’s only a single value, but this seems to have multiple? How do I create an empty array in this fashion … and how would I update/edit it (i tried some simple $array.add() and failed miserably).
So it seems there has to be a way to simply create a multi-valued array without having to resort to imbedding a hashtable … but … well … how?