从.csv添加项目并动态分组

时间:2015-10-01 02:42:53

标签: arrays powershell csv grouping

我正在尝试为用户系统创建代码条目。下面是代码的一个小例子。我可以获得基于.csv创建的用户和组(见下文),但我找不到进入组成员模式的好方法,并根据添加的组添加这些用户(将用户关联到他们的尊重团体)。

它需要遍历组名(基于唯一条目 - 不确定这是否是最好的方式......可能不是)。所以,让我们选择11年级:进入11年级模式(动态地,按照唯一列表),并添加所有需要进入11年级的用户。听起来很简单,一直无法找到方法:\

$path="items.csv"
$All_grades = Import-Csv -path $path | sort grade -Unique 

Write-Host "config users"        #<<---Add Users from .csv

Import-Csv -path $path |

ForEach-Object
{
Write-Host edit id """$($_.id)"""
write-host set grade """$($_.grade)"""
Write-Host set username """$($_.username)"""
Write-Host next
}

Write-Host "config grades"      #<<-----Add Groups from .csv (unique groups)

ForEach ($_ in $All_grades)
{
Write-Host edit $_.grade
write-host set comment """$($_.comment)"""
Write-Host next
}

Write-Host "config group membership"       #<<----Add Group membership based on .csv

ForEach ($All_grades in $path){   #<------- Trying to pick a group from the .csv list, 
    foreach ($_ in $path) #<-------    then look at all usernames and assign correct grade for that user
{                        #<-------     but not working
Write-Host edit  #<------- 
Write-Host set member xy #<--- 
}}

这就是我的.csv文件的样子(items.csv):

id,username,grade,comment
21234,bsmith,10,tenth
21123,djohnson,12,twelveth
11223,jbliss,11,eleventh
21211,atwain,11,eleventh

1 个答案:

答案 0 :(得分:1)

在我看来,Group-Object就是你想要的:

foreach ($gradeGroup in ($All_grades | Group-Object -Property Grade))
{
    Write-Host "Create group $($gradeGroup.Name)"
    foreach ($member in $gradeGroup.Group)
    {
        Write-Host "- Add $($member.username) to $($gradeGroup.Name)"
    } 
}