简体   繁体   English

从json读取数组并传递到Powershell中的变量

[英]Read array from json and pass to variable in Powershell

I'm trying to pass in a list of user and there roles so that I can assign roles to users using powershell. 我正在尝试传递用户列表以及那里的角色,以便可以使用Powershell将角色分配给用户。 I want a json file to contain this information and have the following: 我想要一个json文件包含此信息并具有以下内容:

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

I ran the following Powershell: 我运行了以下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? 我的问题是-然后如何将这些值传递给一个函数,该函数将遍历每个用户并遍历该用户的每个角色,以便我可以运行cmdlet,该cmdlet允许我一次将每个角色分配给一个用户?

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. 我期望有更多的用户和角色,因此json文件将是管理和自动化此任务的最简单方法。

using foreach you can loop through each name and within that loop through of the roles 使用foreach您可以遍历每个name并在各个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

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: 您也可以从User,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}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM