Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an anonymous object in PowerShell?

Tags:

powershell

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 }; 
like image 877
Luke Puplett Avatar asked Mar 18 '16 10:03

Luke Puplett


People also ask

How do I make an anonymous object?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

Can an object be anonymous?

Object expressions You can define them from scratch, inherit from existing classes, or implement interfaces. Instances of anonymous classes are also called anonymous objects because they are defined by an expression, not a name.

How do you add an object in PowerShell?

Use += to Add Objects to an Array of Objects in PowerShell Every time you use it, it duplicates and creates a new array. You can use the += to add objects to an array of objects in PowerShell.


1 Answers

You can do any of the following, in order of easiest usage:

  1. Use Vanilla Hashtable with PowerShell 5+

    In PS5, a vanilla hash table will work for most use cases

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

  2. 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 } 

  3. Using Select-Object cmdlet

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

  4. 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 

  5. 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
like image 92
KyleMit Avatar answered Oct 19 '22 12:10

KyleMit