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:
[pscustomobject]
works reliably with ConvertFrom-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 , namely System.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 .
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.