How do I create an anonymous object in PowerShell?

2020-06-30 05:18发布

问题:

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 };

回答1:

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.



回答2:

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

1. Convert Hashtable to PSCustomObject

$o = [pscustomobject]@{
    Name = "Ted";
    Age = 10
}

2. Using Select-Object cmdlet

$o = Select-Object @{n='Name';e={'Ted'}},
                   @{n='Age';e={10}} `
                   -InputObject ''

3. Using 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

4. Using New-Object and hashtables

$properties = @{
    Name = "Ted";
    Age = 10
}
$o = New-Object psobject -Property $properties;


回答3:

With PowerShell 5+ Just declare as:

    $anon = @{ Name="Ted"; Age= 10; }



标签: powershell