Creating Multi-Dimension Arrays with PSObjects

While working on my book, on my chapter about working with objects, I went through a series of examples on using PSObject and Hash Tables which made me realized that creating NoteProperties is a thing of the past.  Thanks to the “-Property” parameter whe using the New-Object which allows you to use your Hash Table content and build your object Property member type.

New-Object PSObject –Property [HashTable]

Take a look at this previous blog post by the PowerShell Team: http://blogs.msdn.com/b/powershell/archive/2009/12/05/new-object-psobject-property-hashtable.aspx

So, while answering the forum post about “NoteProperties on an ArrayList”, I found myself creating a Multi-Dimension Array on a PSObject.    In my example, I’m trying the create two different Hash Tables, $o1 and $o2, containing the same property with some values.  Then, I’m adding them to the my $a1 PSObject variable using the “+=” operator and this have allow me to create a Multi-Dimension array.

Here’s the code:

## Creating multi-dimension array

[Array] $a1 = $null

$o1= @{ Num = “12”,”34″}

$a1 = new-object PSObject -Property $o1

foreach($i in $a) { $i.num }

$o2 = @{Num = “2”,”4″}

$a1 += new-object PSObject -Property $o2

$a1

foreach($i in $a1) { $i.num }

# Display one of the Dimension Element:
$a1[1].num[1]      # will return value = 4

$a1[0].num[1]      # will return value = 34

Here’s the image with the results:

image

Now, let’s take a look at the $a1 list of member types using Get-Member:

image

Yes, although we use the “-Property” in the New-Object, it will create the NoteProperty for you. 

So would you rather code using Add-Member:

Add-Member -InputObject $o1 -Type NoteProperty -Name Num -Value 12

Or, use the Hash Table concept:

$o1= @{ Num = “12”,”34″}

Well, just let your imagination go!!

%d bloggers like this: