Converting nested hashtables(or yaml) to nested psobject with PowerShell
I'm dabbling with WinGet at work, and I wanted to parse the installer information about VLC Media Player provided by WinGet.
PowerShell does not natively support Yaml, so I like to use the powershell-yaml module.
I thought a simple convert should be enough, but no. This just resulted in a hashtable, I wanted a psobject.
So how about casting ut to a psobject?
Better, at first I thought I was done. But hold on, the properties of Installers are still hashtables. Googling and thinking led me to almost use a recursive function that dealt with this, but then I remembered playing around with conversions between yaml and json. Side note, the UI config of Home Assistant may be edited as yaml, but is stored as json on disk. So I knew they are just different flavors of the same thing, really.
Anyways, this is how to convert yaml to nested psobects:
Get-Content <file.yaml> | ConvertFrom-Yaml | ConvertTo-Json | ConvertFrom-Json
(I added -Depth 5 just because the default value 2 is not enough here. 3 might've been enough, but a little extra doesn't hurt)
Just take a detour into json, those functions seem to handle the recursiveness perfect. I think it's an equally disgusting and beautiful solution.
Now I can easily access the children of Installers and filter them with Where-Object and all the other good stuff.
Hope this is useful to you :)
// Kevin
Comments
Post a Comment