7

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.

2 Answers 2

8

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

Comments

4

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}}

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.