How to create an anonymous object in PowerShell?

I want to create an arbitrary value object, kind of like I can do it in C #

var anon = new { Name = "Ted", Age = 10 }; 
+21
powershell
source share
2 answers

Try the following:

 PS Z:\> $o = @{} PS Z:\> $o.Name = "Ted" PS Z:\> $o.Age = 10 

Note. This object can also be included as -Body for Invoke-RestMethod , and it will serialize it without additional work.

+30
source share

As @Vasyl pointed out above , the accepted answer creates a hash table that actually has no properties, but instead contains a dictionary containing keys and values , so it will work weirdly with some other PS functions

See: [TG42]

Instead, 4 ways to create PowerShell objects , try one 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 the Select-Object

 $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 hash tables

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

All Articles