In PowerShell v3.0 PSCustomObject
was introduced. It's like PSObject
, but better. Among other improvements (e.g. property order being preserved), creating object from hashtable is simplified:
[PSCustomObject]@{one=1; two=2;}
Now it seems obvious that this statement:
[System.Management.Automation.PSCustomObject]@{one=1; two=2;}
would work the same way, because PSCustomObject
is an "alias" for full namespace + class name. Instead I get an error:
Cannot convert the "System.Collections.Hashtable" value of type "System.Collections.Hashtable" to type "System.Management.Automation.PSCustomObject".
I listed accelerators for both types of objects:
[accelerators]::get.GetEnumerator() | where key -Like ps*object
Key Value
--- -----
psobject System.Management.Automation.PSObject
pscustomobject System.Management.Automation.PSObject
and discovered that both reference the same PSObject
class - this has to mean that using accelerators can do a bunch of other stuff than just making the code shorter.
My questions regarding this issue are:
Long description. The [pscustomobject] type accelerator was added in PowerShell 4.0. Prior to adding this type accelerator, creating an object with member properties and values was more complicated. Originally, you had to use New-Object to create the object and Add-Member to add properties.
New-Object creates the object and sets each property value and invokes each method in the order that they appear in the hash table. If the new object is derived from the PSObject class, and you specify a property that does not exist on the object, New-Object adds the specified property to the object as a NoteProperty.
NoteProperties are generic properties that are created by Powershell (as opposed to properties that are inherited from a specific dotnet object type).
Looking at the static methods:
PS C:\> [PSCustomObject] | gm -Static -MemberType Method
TypeName: System.Management.Automation.PSObject
Name MemberType Definition
---- ---------- ----------
AsPSObject Method static psobject AsPSObject(System.Object obj)
Equals Method static bool Equals(System.Object objA, System.Object objB)
new Method psobject new(), psobject new(System.Object obj)
ReferenceEquals Method static bool ReferenceEquals(System.Object objA, System.Object o...
PS C:\> [System.Management.Automation.PSCustomObject] | gm -Static -MemberType Method
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method static bool Equals(System.Object objA, System.Object objB)
ReferenceEquals Method static bool ReferenceEquals(System.Object objA, System.Object o...
The type accelerator has a couple of new static methods added. I suspect it's using one of those as the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With