How to convert JSON object to Hashtable format using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

PowerShell 7 supports the -AsHashtable parameter in the ConvertFrom−JSON command to convert the JSON to hashtable directly and that is a great feature. Consider we have the below JSON file,

We can use the pipeline command ConvertFrom−JSON to convert the JSON file to the custom table format and with the −AsHashtable parameter to convert the custom object to the hashtable.

PS C:\Temp> Get-Content .\testsevent.json | ConvertFrom-Json -AsHashtable
Name Value
---- -----
Events {602d9444−d2cd−49c7−8624−8643e7171297}
DocumentIncarnation 0

To retrieve the data,

PS C:\Temp> $out = Get−Content .\testsevent.json | ConvertFrom−Json −AsHashtable
PS C:\Temp> $out.Events


PS C:\Temp> $out.Events
Name Value
---- -----
Description Host server is undergoing maintenance.
EventStatus Scheduled
EventId 602d9444−d2cd−49c7−8624−8643e7171297

For the PowerShell framework version, −AsHashTable parameter is not supported and in that case, you need to convert it to the hashtable manually as shown below.

$out = Get−Content .\testsevent.json | ConvertFrom−Json

Code to convert JSON to Hashtable,

$hash = @{}
$ | foreach{$hash[$_.Name]= $_.Value}


Published on 25-Jan-2021 07:22:26