Iterating through key names from a PSCustomObject

前端 未结 2 749
花落未央
花落未央 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:28

    Solution

    I'm not sure how early of a version you can do this with, but it works for me in PowerShell 5.1... Feel free to give it a try in earlier versions:

    $ipinfo = Invoke-WebRequest 'http://ipinfo.io/json' -UseBasicParsing | ConvertFrom-Json
    foreach ($info in $ipinfo.PSObject.Properties) {
        $info.Name
        $info.Value
        '--' # <-- Seeing this double hash proves we're iterating fully.
    }
    

    Outputs

    ip
    1.2.3.4
    --
    hostname
    No Hostname
    --
    city
    Denton
    --
    region
    Texas
    --
    country
    US
    --
    loc
    33.2148,-97.1331
    --
    org
    AS589 University of North Texas
    --
    postal
    76203
    --
    

    This is all done with PowerShell 4.0; ConvertTo-Json and ConvertFrom-Json were introduced in PowerShell 3.0; I haven't tested PowerShell 3.0 or 5.0.


    Another Example

    Try it for yourself with another example:

    $ipinfo = ConvertFrom-Json (Invoke-WebRequest 'http://ipinfo.io/json' -UseBasicParsing)
    foreach ($info in ($ipinfo.PSObject.Members | ?{ $_.MemberType -eq 'NoteProperty'})) {
        $info.Name
        $info.Value
        '--'
    }
    

    Outputs

    ip
    1.2.3.4
    --
    hostname
    No Hostname
    --
    city
    Denton
    --
    region
    Texas
    --
    country
    US
    --
    loc
    33.2148,-97.1331
    --
    org
    AS589 University of North Texas
    --
    postal
    76203
    --
    

    This and other PowerShell looping are available on my blog.

提交回复
热议问题