I am working to build a way to iterate through all the key value pairs of a PSObject that was created by using ConvertFrom-Json.
To do this, I need a way to know if a given PSObject has one or more children.
So, given the following JSON:
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
I run this code:
$settings = Get-Content -Raw $pathToFile | ConvertFrom-Json
foreach ($base in $settings.PSObject.Properties)
{
if ($base.HasChildren -eq $true)
{
// Iterate Deeper
}
}
When I am on the "Logging" node, $base has true for HasChildren but AllowedHosts has false.
Obviously, there is no such method of HasChildren, so this would not work. But I am wondering if there is a a way to find this out?
What
ConvertFrom-Jsonoutputs is a[pscustomobject]graph, so you can indeed test properties of that graph enumerated via the intrinsicpsobjectproperty for being instances of that type using-is, the type(-inheritance) / interface test operator, as Santiago Squarzon suggests:Note:
[pscustomobject]works reliably withConvertFrom-Json, but - for obscure technical reasons - the generally more robust solution is to use the (technically incorrect)[System.Management.Automation.PSCustomObject]. Surprisingly,[pscustomobject]is the same as[psobject], whose full type name is different, namelySystem.Management.Automation.PSObject. See GitHub issue #11921 for background information.There are many answers on this site that show how to recursively walk a
[pscustomobject]graph, such as this answer.