我想从不同的Active Directory组中读取用户,然后对结果进行排序和分组。 从像
这样的列表中UserName UserGroup UZZ GAA UKK GAA UZZ GBB ULL GBB
我希望得到:
Username UserGroup UKK GAA ULL GBB UZZ GAA
因此,从User UZZ我想在列表中只获得一个条目,其中第一个值为UserGroup(首先是字母数字排序)。 直到现在我有以下代码:
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "G-Q-T*"} | select name -expandproperty name)
$Table = @()
$Record = @{"GroupName" = """Username" = ""}
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name, samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."GroupName" = $Group
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objRecord
}
}
$Table | Sort-object -property Username | Group-object -property Username | export-csv "U:\members.csv" -NoTypeInformation**
制作列表的部分工作正常。但不是排序和小组的一部分。 非常感谢您的回答和帮助。
同时我发现,我还要将SID添加到.csv文件中。 SID也在Get-AdGroupMember中。但后来我尝试实现如下,在SID的情况下输出保持为空。我错在哪里?提前感谢您的回答:
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter "name -like 'G-Q-T*'" | select name -expandproperty name)
$Table = @()
$Record = @{
"GroupName" = ""
"Username" = ""
"SID" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname,SID
foreach ($Member in $Arrayofmembers)
{
$Record."GroupName" = $Group
$Record."UserName" = $Member.samaccountname
$Record."SID" = $Member.SID
$objRecord = New-Object PSObject -property $Record
$Table += $objRecord
}
}
$Table | Group-Object -Property Username |
Select-Object @{n="UserName";e={$_.Name}} , @{n="GroupName";e={$_.Group | Sort-Object GroupName | Select-Object -First 1 -ExpandProperty GroupName}} , @{n="SID";e={$_.SID | Sort-Object SID | Select-Object -First 1 -ExpandProperty SID}}| Export-Csv "U:\member.csv" -NoTypeInformation
答案 0 :(得分:0)
我会对用户名进行分组,并使用计算属性来创建所需的结果。对组中的组名进行排序,然后选择第一个值。尝试用以下代码替换你的最后一行:
$Table | Group-Object -Property Username |
Select-Object @{n="UserName";e={$_.Name}}, @{n="GroupName";e={$_.Group | Sort-Object GroupName | Select-Object -First 1 -ExpandProperty GroupName}} |
Export-Csv "U:\members.csv" -NoTypeInformation
在检索每个组时避免使用-Filter *
。用它来获取你需要的组
$Groups = Get-ADGroup -Filter "name -like 'G-Q-T*'"
替代使用着名的管道:
Get-ADGroup -Filter "name -like 'G-Q-T*'" | ForEach-Object {
$groupname = $_.Name
$_ | Get-ADGroupMember | ForEach-Object {
New-Object -TypeName psobject -Property @{
UserName = $_.SamAccountName
SID = $_.SID
GroupName = $groupname
}
}
} | Group-Object -Property UserName |
Select-Object @{n="UserName";e={$_.Name}}, @{n="SID";e={$_.Group[0].SID}}, @{n="GroupName";e={$_.Group | Sort-Object GroupName | Select-Object -First 1 -ExpandProperty GroupName}} |
Export-Csv "U:\members.csv" -NoTypeInformation