I want to create an object of arbitrary values, sort of like how I can do this in C#
var anon = new { Name = "Ted", Age = 10 };
I want to create an object of arbitrary values, sort of like how I can do this in C#
var anon = new { 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.
As @Vasyl pointed out above, the accepted answer creates a hashtable, which doesn't actually have properties, but instead a dictionary containtaining keys
and values
so it will work weird with some other PS functions
See: $o | Select -Property *
Instead, per 4 Ways to Create PowerShell Objects, try any of the following:
#1 is probably the newest and easiest syntax unless you have a strong preference
PSCustomObject
$o = [pscustomobject]@{
Name = "Ted";
Age = 10
}
Select-Object
cmdlet$o = Select-Object @{n='Name';e={'Ted'}},
@{n='Age';e={10}} `
-InputObject ''
New-Object
and Add-Member
$o = New-Object -TypeName psobject
$o | Add-Member -MemberType NoteProperty -Name Name -Value 'Ted'
$o | Add-Member -MemberType NoteProperty -Name Age -Value 10
New-Object
and hashtables$properties = @{
Name = "Ted";
Age = 10
}
$o = New-Object psobject -Property $properties;
With PowerShell 5+ Just declare as:
$anon = @{ Name="Ted"; Age= 10; }