Export-csv:合并重复行

时间:2014-03-28 13:49:25

标签: powershell csv powershell-v3.0

全部,感谢问题Edit a script I found to import a list of adusers, grab their info and export back to another csv中的解决方案,我能够提出以下脚本。脚本从csv文件中提取用户名,连接到广告,并将用户组导出到不同的csv。那部分完美无缺。这是我遇到问题的地方。每个用户名/组都被放入一个新行。除了多个组中的用户之外,这是完美的。例如

ColA     ColB
User     Group
bob      admin 
jeff     domain admin  
jeff     test admin 
jeff     power user 

我想要做的是以下列格式导出导出方式

ColA     ColB           ColC          ColD   
User     Group          Group         Group
bob      admin
jeff     domian admin   test admin    power user 

这是我的剧本

Begin {
Try { Import-Module ActiveDirectory -ErrorAction Stop }
Catch { Write-Host "Unable to load Active Directory module, is RSAT installed?"; Break }
}

Process {
$UserList=Get-Content C:\Userlist.csv
$users = ForEach ($U in $UserList)
{   $UN = Get-ADUser $U -Properties MemberOf
$Groups = ForEach ($Group in ($UN.MemberOf))
{   (Get-ADGroup $Group).Name
} 
$Groups = $Groups | Sort
ForEach ($Group in $Groups)
{   New-Object PSObject -Property @{
        Name = $UN.Name
        Group = $Group
    } 
} 
} 
$users | export-csv "c:\grouptest.csv" -append
} 

可以这样做吗?

1 个答案:

答案 0 :(得分:0)

除非我误解了你的目标,否则你只需要替换它:

ForEach ($Group in $Groups)
{   New-Object PSObject -Property @{
        Name = $UN.Name
        Group = $Group
    } 
}

用这个:

New-Object PSObject -Property @{
    Name  = $UN.Name
    Group = $Groups
}