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.