Create A PowerShell Hash Table From A PowerShell Object

April 11, 2011

in .Net,Microsoft,PowerShell

Matt Biehl asks: How would you create a hash table from a PowerShell objects properties?

Matt takes a hash table (associative array) and creates a .Net object (PSObject) with properties and values by passing it to the Property parameter on the New-Object.

$peeps = @{
  'Lead'='asmith';
  'Enterprise'='bjones';
  'Edge'='chumperdink';
  'Backend'='dwilford';
  'SED'='fhanns'
}            

$obj = New-Object -Type PSObject -Property $peeps

Turn A PowerShell Object Into a Hash Table

I pipe the newly created object to Get-Member filtering out only the properties using the MemberType parameter (see Results of the Get-Member). I then use the Begin/Process/End block of the ForEach.

In the Begin Block I create the $hash and in the End Block I “return” the $hash. Which in this case prints it out.

In Process Block, I grab the $_.Name from the Get-Member results. In the 3rd line, on the left hand side of the equals I create the hash key using dot notation and then set the value on the right hand side using the same $_.Name and dot notation but using the $obj which contains the value.

$obj | Get-Member -MemberType Properties |
    ForEach {$hash=@{}} {
        $hash.($_.Name) = $obj.($_.Name)
    } {$hash}            

# Results
Name                           Value
----                           -----
Backend                        dwilford
SED                            fhanns
Edge                           chumperdink
Lead                           asmith
Enterprise                     bjones

Results of the Get-Member

$obj | Get-Member -MemberType Properties            

# Results of Get-Member

  TypeName: System.Management.Automation.PSCustomObject

Name       MemberType   Definition
----       ----------   ----------
Backend    NoteProperty System.String Backend=dwilford
Edge       NoteProperty System.String Edge=chumperdink
Enterprise NoteProperty System.String Enterprise=bjones
Lead       NoteProperty System.String Lead=asmith
SED        NoteProperty System.String SED=fhanns

{ 2 comments… read them below or add one }

BHarat 07.13.11 at 6:15 pm

$Obj | ForEach-Object{$hash.Add($_.Name, $_.Count)}

will work if your object have only two properties alone

Doug Finke 07.14.11 at 8:12 am

Good shortcut.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Contrat Creative Commons

© 2007-2012, Doug Finke