How do I create an anonymous object in PowerShell?
With PowerShell 5+ Just declare as:
$anon = @{ Name="Ted"; Age= 10; }
Try this:
PS Z:\> $o = @{}
PS Z:\> $o.Name = "Ted"
PS Z:\> $o.Age = 10
Note: You can also include this object as the -Body
of an Invoke-RestMethod
and it'll serialize it with no extra work.
Update
Note the comments below. This creates a hashtable.
You can do any of the following, in order of easiest usage:
Use Vanilla Hashtable with PowerShell 5+
In PS5, a vanilla hash table will work for most use cases
$o = @{ Name = "Ted"; Age = 10 }
Convert Hashtable to
PSCustomObject
If you don't have a strong preference, just use this where vanilla hash tables won't work:
$o = [pscustomobject]@{ Name = "Ted"; Age = 10 }
Using
Select-Object
cmdlet$o = Select-Object @{n='Name';e={'Ted'}}, @{n='Age';e={10}} ` -InputObject ''
Using
New-Object
andAdd-Member
$o = New-Object -TypeName psobject $o | Add-Member -MemberType NoteProperty -Name Name -Value 'Ted' $o | Add-Member -MemberType NoteProperty -Name Age -Value 10
Using
New-Object
and hashtables$properties = @{ Name = "Ted"; Age = 10 } $o = New-Object psobject -Property $properties;
Note: Objects vs. HashTables
Hashtables are just dictionaries containing keys
and values
, meaning you might not get the expected results from other PS functions that look for objects
and properties
:
$o = @{ Name="Ted"; Age= 10; }
$o | Select -Property *
Further Reading
- 4 Ways to Create PowerShell Objects
- Everything you wanted to know about
hashtables
- Everything you wanted to know about
PSCustomObject