Can I get hierarchy path for property in json using powershell?

Viewed 215

Consider that json object:

@"
        {
          ""Logging"": {
            ""LogLevel"": {
              ""Default"": ""Warning""
            }
          },
          ""AllowedHosts"": ""*"",
          ""ConnectionStrings"": {
            ""ConnectionString1"": """",
            ""ConnectionString2"": """",
            ""ConnectionString3"": """"
            }}"; 

I want to write a function in powershell that will take that json and search for certain property and return the path of it. For instance if the function name is ReturnHierarchyPath(json, propertyName)

When I call it ReturnHierarchyPath(json, "ConnectionString1") , the return should be "ConnectionStrings.ConnectionString1"

I implemeted this in C# but I want to know if it's possible in powershell script?

Here is the example of the C# code: https://dotnetfiddle.net/N5ccWY

1 Answers

In your C# example, you are relying on LINQ to do some of the heavy lifting.

To do this in Powershell I think the easiest way is to just convert to JSON into a Powershell object and then recursively evaluate all the properties while storing up the built up path.

The [CmdletBinding()] and Verbose stuff are not neccessary, but I find it really useful to be able to see how the execution flows when writing functions like this.

I think this will do pretty much exactly what you asked for:

Function ReturnHierarchy {
    [CmdletBinding()]
    Param(
        [PSObject]$Object,
        [string]$PropertyName,
        [string[]]$Path = @()
    )

    if (!$Object) { return }

    return $Object.PSObject.Properties.Name | % {
        Write-Verbose "Checking property $(($Path + $_) -join ".")"
        ReturnHierarchy -Object $Object.$_ -PropertyName $PropertyName -Path ($Path + $_)

        if ($_ -like $PropertyName)  {
            return ($Path + $_) -join "."
        }
    }
}

$obj = @"
{
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "ConnectionString1": "",
        "ConnectionString2": "",
        "ConnectionString3": ""
    }
}
"@ | ConvertFrom-Json

ReturnHierarchy -Object $obj -PropertyName "ConnectionString1" -Verbose
Related