简体   繁体   中英

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

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 aa way to find this out?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM