2

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 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, @Cbsch! That is exactly what I'm looking for. I'm sure others will find this function very useful too.
May not work for array though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.