Converting Hash Tables to Objects

Hash Tables are convenient but are not true objects. This is bad because you are unable to output the hash content to formatting cmdlets or export cmdlets. With a short function, you can easily convert a Hash Table to an object, providing all the flexibility you need to forward the object to other cmdlets like Format-Table or Export-CSV:

function ConvertTo-Object($hashtable) 
{
$object = New-Object PSObject
$hashtable.GetEnumerator() |
ForEach-Object { Add-Member -inputObject $object `
-memberType NoteProperty -name $_.Name -value $_.Value }
$object
}

$hash = @{Name='Tobias'; Age=66; Status='Online'}
$hash
ConvertTo-Object $hash

Posted Nov 14 2008, 08:00 AM by ps1

Comments

Tobias Weltner wrote re: Converting Hash Tables to Objects
on 11-17-2008 5:22 AM

You can also turn this into a pipeline filter. It may be easier to pipe hashtables into this function, and also this way you can combine a number of hashtables into one object:

function ConvertTo-Object {

begin { $object = New-Object Object }

process {

$_.GetEnumerator() | ForEach-Object { Add-Member -inputObject $object -memberType NoteProperty -name $_.Name -value $_.Value }  

}

end { $object }

}

$hash1 = @{name='Melzer';firstname='Tim';age=68}

$hash2 = @{id=12;count=100;remark='Second Hash Table'}

$hash1, $hash2 | ConvertTo-Object

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.