Hashtables from ConvertFrom-json have different type from powershells built-in hashtables, how do I make them the same?

前端 未结 5 1301
天命终不由人
天命终不由人 2020-12-09 10:33

I have a json file (test.json) that looks something like this:

{
    \"root\":
    {
        \"key\":\"value\"
    }
}

I\'m loading it into

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 10:49

    Here's a quick function to convert a PSObject back into a hashtable (with support for nested objects; intended for use with DSC ConfigurationData, but can be used wherever you need it).

    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
            }
        }
    }
    

提交回复
热议问题