Is there a way to tell if a PSObject has children?

172 Views Asked by At

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?

1

There are 1 best solutions below

0
mklement0 On

What ConvertFrom-Json outputs is a [pscustomobject] graph, so you can indeed test properties of that graph enumerated via the intrinsic psobject property for being instances of that type using -is, the type(-inheritance) / interface test operator, as Santiago Squarzon suggests:

foreach ($base in $settings.PSObject.Properties) {
    if ($base.Value -is [pscustomobject]) {
        # Iterate Deeper
    }
}

Note: