powershellhashtablepscustomobject

PSCustomObject to Hashtable


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?


Solution

  • 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 }
    $theObject = new-object psobject -Property $ht1
    
    # Convert the PSCustomObject back to a hashtable
    $ht2 = @{}
    $theObject.psobject.properties | Foreach { $ht2[$_.Name] = $_.Value }