Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between PSObject, Hashtable, and PSCustomObject

Can anybody explain the details? If I create an object using

$var = [PSObject]@{a=1;b=2;c=3} 

and then I look for its type using getType() PowerShell tells me it's of type Hashtable.

When using Get-Member (alias gm) to inspect the object it's obvious that a hashtable has been created, since it has a keys and a values property. So what's the difference to a "normal" hashtable?

Also, what's the advantage of using a PSCustomObject? When creating one using something like this

$var = [PSCustomObject]@{a=1;b=2;c=3} 

the only visible difference to me is the different datatype of PSCustomObject. Also instead of keys and value properties, a inspection with gm shows that now every key has been added as a NoteProperty object.

But what advantages do I have? I'm able to access my values by using its keys, just like in the hashtable. I can store more than simple key-value pairs (key-object pairs for example) in the PSCustomObject, JUST as in the hashtable. So what's the advantage? Are there any important differences?

like image 545
omni Avatar asked Dec 23 '12 16:12

omni


1 Answers

One scenario where [PSCustomObject] is used instead of HashTable is when you need a collection of them. The following is to illustrate the difference in how they are handled:

$Hash = 1..10 | %{ @{Name="Object $_" ; Index=$_ ; Squared = $_*$_} } $Custom = 1..10 | %{[PSCustomObject] @{Name="Object $_" ; Index=$_ ; Squared = $_*$_} }  $Hash   | Format-Table -AutoSize $Custom | Format-Table -AutoSize  $Hash   | Export-Csv .\Hash.csv -NoTypeInformation $Custom | Export-Csv .\CustomObject.csv -NoTypeInformation 

Format-Table will result in the following for $Hash:

Name    Value ----    ----- Name    Object 1 Squared 1 Index   1 Name    Object 2 Squared 4 Index   2 Name    Object 3 Squared 9 ... 

And the following for $CustomObject:

Name      Index Squared ----      ----- ------- Object 1      1       1 Object 2      2       4 Object 3      3       9 Object 4      4      16 Object 5      5      25 ... 

The same thing happens with Export-Csv, thus the reason to use [PSCustomObject] instead of just plain HashTable.

like image 151
tkokasih Avatar answered Sep 29 '22 20:09

tkokasih