Iterating through key names from a PSCustomObject

前端 未结 2 747
花落未央
花落未央 2021-02-13 11:10

I am writing a script for my site that utilizes a JSON configuration file. The JSON is similar to the following:

\"Groups\": {
    \"GroupOne\": {
        \"Nami         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 11:25

    I think I might have just figured it out thanks to the blog post Converting PsCustomObject To/From Hashtables.

    Using Get-Member and then -MemberType exposes each Group and then you just pull the:

    foreach ($group in $configObject.Groups) {
        $groupName = $($group | Get-Member -MemberType *Property).Name
    }
    

    Outputs:

    GroupOne
    GroupTwo
    GroupThree
    

    I'm open to any other methods though.

    Update

    I've found another way, but the only drawback is it doesn't use the fancy ConvertFrom-Json CmdLet. Instead it goes straight to the .NET library and uses its deserializer and converts it to a HashTable. This completely avoids having to muddle around with the PSCustomObject. IMO hashtables are a whole lot easier to work with.

    $JSON = Get-Content -Path path/to.json -Raw
    $HT = (New-Object System.Web.Script.Serialization.JavaScriptSerializer).Deserialize($JSON, [System.Collections.Hashtable])
    $HT.Groups.GetEnumerator() | ForEach-Object {
        Write-Host "$($_.Key) : $($_.Value)"
    }
    

提交回复
热议问题