Read array from json and pass to variable in Powershell

15,483

Solution 1

using foreach you can loop through each name and within that loop through of the roles

$json | foreach {
    $user = $_.name
    $_.roles | foreach {
        $role = $_
        Write-Output "User: $user"
        Write-Output "Role: $role"
        #Add-RoleToUser $user $role
    }
}
User: User1
Role: System Administrator
User: User1
Role: System User
User: User2
Role: System User

Solution 2

To have a different iterating variable

ForEach ($User in $json){
    "User: {0}" -f $User.name

    ForEach ($Role in $User.roles){
        "      Role: {0}" -f $Role

    }
}

Sample output:

User: User1
      Role: System Administrator
      Role: System User
User: User2
      Role: System User

You could as well build a new object from User,Role and group that by role:

$UserRoles = ForEach ($User in $json){
    ForEach ($Role in $User.roles){
        [PSCustomObject]@{
            User = $User.Name
            Role = $Role
        }
    }
}

$UserRoles | Group Role

> $UserRoles | Group Role

Count Name                      Group
----- ----                      -----
    1 System Administrator      {@{User=User1; Role=System Administrator}}
    2 System User               {@{User=User1; Role=System User}, @{User=User2; Role=System User}}
Share:
15,483

Related videos on Youtube

darren25
Author by

darren25

Updated on June 04, 2022

Comments

  • darren25
    darren25 almost 2 years

    I'm trying to pass in a list of user and there roles so that I can assign roles to users using powershell. I want a json file to contain this information and have the following:

    [
       {
          "name":"User1",
          "roles":[
             "System Administrator",
             "System User"
          ]
       },
       {
          "name":"User2",
          "roles":[
             "System User"
          ]
       }
    ]
    

    I ran the following Powershell:

    $json = Get-Content -Raw -Path C:\temp\ExampleJsonArray.json | ConvertFrom-Json
    

    This gives me:

    name  roles                              
    ----  -----                              
    User1 {System Administrator, System User}
    User2 {System User}  
    

    My question is - how do I then pass these values into a function that will loop through each user and loop through each role for the user so I can run the cmdlet that allows me to assign each role to a user one at a time?

    add-RoleToUser $user $role
    

    Above is just a basic example. I'm expecting many more users and roles so though a json file would be the easiest way to manager and automate this task.