0

As I am new to Powershell, can someone please support on the looping part? Below is the json format from Test.json file:

{
    "Pre-Production_AFM": {
        "allowedapps": ["app1", "app2"]
    },
    "Production_AFM": {
        "allowedapps": ["app1", "app2"]
    }
}

I am reading the json file as below

$json = (Get-Content "Test.json" -Raw) | ConvertFrom-Json

I need to loop and get the 1st and 2nd objects - "Pre-Production_AFM" and "Production_AFM" one after another dynamically.

right now I have written the code as below :

foreach($i in $json){

        if($i -contains "AFM"){
       Write host "execute some code"
     }
}

My dout is - Will $i holds the object "Pre-Production_AFM" dynamically? If not please suggest the way to get the objects one after one dynamically for further execution.

1 Answer 1

1
# read the json text
$json = @"
{
    "Pre-Production_AFM": {
        "allowedapps": ["app1", "app2"]
    },
    "Production_AFM": {
        "allowedapps": ["app1", "app2"]
    }
}
"@

# convert to a PSCustomObject
$data = $json | ConvertFrom-Json

# just to prove it's a PSCustomObject...
$data.GetType().FullName
# System.Management.Automation.PSCustomObject

# now we can filter the properties by name like this:
$afmProperties = $data.psobject.Properties | where-object { $_.Name -like "*_AFM" };

# and loop through all the "*_AFM" properties
foreach( $afmProperty in $afmProperties )
{
   $allowedApps = $afmProperty.Value.allowedApps
   # do stuff
}
Sign up to request clarification or add additional context in comments.

Comments

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.