PSCustomObject to Hashtable PSCustomObject to Hashtable powershell powershell

PSCustomObject to Hashtable


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 }


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}


Here's a version that works with nested hashtables / arrays as well (which is useful if you're trying to do this with DSC ConfigurationData):

function ConvertPSObjectToHashtable{    param (        [Parameter(ValueFromPipeline)]        $InputObject    )    process    {        if ($null -eq $InputObject) { return $null }        if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string])        {            $collection = @(                foreach ($object in $InputObject) { ConvertPSObjectToHashtable $object }            )            Write-Output -NoEnumerate $collection        }        elseif ($InputObject -is [psobject])        {            $hash = @{}            foreach ($property in $InputObject.PSObject.Properties)            {                $hash[$property.Name] = ConvertPSObjectToHashtable $property.Value            }            $hash        }        else        {            $InputObject        }    }}