Creating a custom object from a hash table
A
hash table can be turned into a custom object like so:
PS C:\> $hashTable = @{key_1 = 'foo'; key_2 = 'bar'; key_3 = 'baz' }
PS C:\> $hashTable
Name Value
---- -----
key_1 foo
key_3 baz
key_2 bar
PS C:\> $hashTable | get-member -memberType properties
TypeName: System.Collections.Hashtable
Name MemberType Definition
---- ---------- ----------
…
Keys Property System.Collections.ICollection Keys {get;}
…
Values Property System.Collections.ICollection Values {get;}
PS C:\> $custObj = new-object psObject -property $hashTable
PS C:\> $custObj
key_1 key_3 key_2
----- ----- -----
foo baz bar
PS C:\> $custObj | get-member -memberType properties
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
key_1 NoteProperty string key_1=foo
key_2 NoteProperty string key_2=bar
key_3 NoteProperty string key_3=baz
It is even simpler (and as some sources on the internet seem to claim also faster) to use the
[psCustomObject]
type accelerator:
PS C:\> $anotherObj = [psCustomObject] @{ K1 = 'one'; K2 = 'two'; K3 = 'three' }