tags:

views:

37

answers:

2

What is the easiest way to convert a PSCustomObject to a Hashtable. It displays just like one with the splat operator, curly braces and what appear to be key value pairs. When I try to cast it to [Hashtable] it doesn't work. I also tried .toString() and the assigned variable says its a string but displays nothing - any ideas?

+3  A: 

Shouldn't be too hard. Something like this should do the trick:

# Create a PSCustomObject (ironically using a hashtable)
$ht1 = @{ A = 'a'; B = 'b'; DateTime = Get-Date }
$psobject = new-object psobject -Property $ht1

# Convert the PSCustomObject back to a hashtable
$ht2 = @{}
$psobject.psobject.properties | Foreach { $ht2["$($_.Name)"] = $_.Value }
Keith Hill
+1  A: 

Keith already gave you the answer, this is just another way of doing the same with a one-liner:

$psobject.psobject.properties | foreach -begin {$h=@{}} -process {$h."$($_.Name)" = $_.Value} -end {$h}
Shay Levy
Heh, started with something very similar except that it was just long enough to invoke the SO horizontal scrollbar. BTW I think your `$'s` are missing some `_'s`. :-)
Keith Hill
That's what I was trying to avoid and eventually it swallowed the underscore sign. Thanks!
Shay Levy