Difference between PSObject, Hashtable, and PSCustomObject

PowershellPowershell 3.0Psobject

Powershell Problem Overview


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?

Powershell Solutions


Solution 1 - Powershell

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.

Solution 2 - Powershell

Say I want to create a folder. If I use a PSObject you can tell it is wrong by looking at it

PS > [PSObject] @{Path='foo'; Type='directory'}

Name                           Value
----                           -----
Path                           foo
Type                           directory

However the PSCustomObject looks correct

PS > [PSCustomObject] @{Path='foo'; Type='directory'}

Path                                    Type
----                                    ----
foo                                     directory

I can then pipe the object

[PSCustomObject] @{Path='foo'; Type='directory'} | New-Item

Solution 3 - Powershell

From the PSObject documentation:

> Wraps an object providing alternate views of the available members and ways to extend them. Members can be methods, properties, parameterized properties, etc.

In other words, a PSObject is an object that you can add methods and properties to after you've created it.

From the "About Hash Tables" documentation:

> A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs. > > ... > > Hash tables are frequently used because they are very efficient for finding and retrieving data.

You can use a PSObject like a Hashtable because PowerShell allows you to add properties to PSObjects, but you shouldn't do this because you'll lose access to Hashtable specific functionality, such as the Keys and Values properties. Also, there may be performance costs and additional memory usage.

The PowerShell documentation has the following information about PSCustomObject:

> Serves as a placeholder BaseObject when PSObject's constructor with no parameters is used.

This was unclear to me, but a post on a PowerShell forum from the co-author of a number of PowerShell books seems more clear:

> [PSCustomObject] is a type accelerator. It constructs a PSObject, but does so in a way that results in hash table keys becoming properties. PSCustomObject isn't an object type per se – it's a process shortcut. ... PSCustomObject is a placeholder that's used when PSObject is called with no constructor parameters.

Regarding your code, @{a=1;b=2;c=3} is a Hashtable. [PSObject]@{a=1;b=2;c=3} doesn't convert the Hashtable to a PSObject or generate an error. The object remains a Hashtable. However, [PSCustomObject]@{a=1;b=2;c=3} converts the Hashtable into a PSObject. I wasn't able to find documentation stating why this happens.

If you want to convert a Hashtable into an object in order to use its keys as property names you can use one of the following lines of code:

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

# OR

New-Object PSObject -Property @{a=1;b=2;c=3}

# NOTE: Both have the type PSCustomObject

If you want to convert a number of Hashtables into an object where their keys are property names you can use the following code:

@{name='a';num=1},@{name='b';num=2} |
 % { [PSCustomObject]$_ }

# OR

@{name='a';num=1},@{name='b';num=2} |
 % { New-Object PSObject -Property $_ }

<#
Outputs:

name num
---- ---
a      1
b      2
#>

Finding documentation regarding NoteProperty was difficult. In the Add-Member documentation, there isn't any -MemberType that makes sense for adding object properties other than NoteProperty. The Windows PowerShell Cookbook (3rd Edition) defined the Noteproperty Membertype as:

> A property defined by the initial value you provide > > - Lee, H. (2013). Windows PowerShell Cookbook. O'Reilly Media, Inc. p. 895.

Solution 4 - Powershell

One advantage I think for PSObject is that you can create custom methods with it.

For example,

$o = New-Object PSObject -Property @{
   "value"=9
}
Add-Member -MemberType ScriptMethod -Name "Sqrt" -Value {
    echo "the square root of $($this.value) is $([Math]::Round([Math]::Sqrt($this.value),2))"
} -inputObject $o

$o.Sqrt()

You can use this to control the sorting order of the PSObject properties (see https://stackoverflow.com/questions/18825419/psobject-sorting/18826004#18826004)

Solution 5 - Powershell

I think the biggest difference you'll see is the performance. Have a look at this blog post:

Combining Objects Efficiently – Use a Hash Table to Index a Collection of Objects

The author ran the following code:

$numberofobjects = 1000

$objects = (0..$numberofobjects) |% {
    New-Object psobject -Property @{'Name'="object$_";'Path'="Path$_"}
}
$lookupobjects = (0..$numberofobjects) | % {
    New-Object psobject -Property @{'Path'="Path$_";'Share'="Share$_"}
}

$method1 = {
    foreach ($object in $objects) {
        $object | Add-Member NoteProperty -Name Share -Value ($lookupobjects | ?{$_.Path -eq $object.Path} | select -First 1 -ExpandProperty share)
    }
}
Measure-Command $method1 | select totalseconds

$objects = (0..$numberofobjects) | % {
    New-Object psobject -Property @{'Name'="object$_";'Path'="Path$_"}
}
$lookupobjects = (0..$numberofobjects) | % {
    New-Object psobject -Property @{'Path'="Path$_";'Share'="Share$_"}
}

$method2 = {
    $hash = @{}
    foreach ($obj in $lookupobjects) {
        $hash.($obj.Path) = $obj.share
    }
    foreach ($object in $objects) {
        $object |Add-Member NoteProperty -Name Share -Value ($hash.($object.path)).share
    }
}
Measure-Command $method2 | select totalseconds

Blog author's output:

TotalSeconds
------------
 167.8825285
   0.7459279

His comment regarding the code results is:

> You can see the difference in speed when you put it all together. The object method takes 167 seconds on my computer while the hash table method will take under a second to build the hash table and then do the lookup.

Here are some of the other, more-subtle benefits: Custom objects default display in PowerShell 3.0

Solution 6 - Powershell

We have a bunch of templates in our Windows-PKI and we needed a script, that has to work with all active templates. We do not need to dynamically add templates or remove them. What for me works perfect (since it is also so "natural" to read) is the following:

$templates = @(
    [PSCustomObject]@{Name = 'template1'; Oid = '1.1.1.1.1'}
    [PSCustomObject]@{Name = 'template2'; Oid = '2.2.2.2.2'}
    [PSCustomObject]@{Name = 'template3'; Oid = '3.3.3.3.3'}
    [PSCustomObject]@{Name = 'template4'; Oid = '4.4.4.4.4'}
    [PSCustomObject]@{Name = 'template5'; Oid = '5.5.5.5.5'}
)

foreach ($template in $templates)
{
   Write-Output $template.Name $template.Oid
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomniView Question on Stackoverflow
Solution 1 - PowershelltkokasihView Answer on Stackoverflow
Solution 2 - PowershellZomboView Answer on Stackoverflow
Solution 3 - PowershellDave FView Answer on Stackoverflow
Solution 4 - PowershellLoïc MICHELView Answer on Stackoverflow
Solution 5 - PowershellAdam DriscollView Answer on Stackoverflow
Solution 6 - Powershelluser15386446View Answer on Stackoverflow