导出多个组的成员

Export members of multiple groups

是否可以通过两种方式更改下面的 PS 脚本:

  1. 组成员现在水平导出,但我希望所有用户都在组名称旁边的列中的 1 个单元格中。我们有很多组,这样读起来不方便。
  2. 不导出AD组描述字段中的文件夹路径。我想把描述字段的内容也导出到组旁边的列中。

我想看看这个结果,请看下面的照片:

cls
$Groups = "Group1", "Group2", "Group3"
$results = foreach ($Group in $Groups) {
  Get-ADGroupMember -Server contoso.com $group | 
    select SamAccountName, @{n='GroupName';e={$group}}, @{n='Description';e={(Get-ADGroup $group -Properties description).description}}
}
$results
$results | Export-csv C:\TEMP\GroupMemberShip.CSV -NoTypeInformation 

通过对您的原始代码进行一些小改动,您可以先收集每个组所需的信息,然后在导出为 CSV 之前,使用 Group-Object 合并详细信息。

类似于:

$Groups = "Group1", "Group2", "Group3"
$results = foreach ($Group in $Groups) {
    $adGroup = Get-ADGroup $group -Properties Description -ErrorAction SilentlyContinue
    if ($adGroup) {
        $adGroup | Get-ADGroupMember -Server 'contoso.com' | 
        Select-Object SamAccountName, 
                      @{Name = 'GroupName'; Expression = {$adGroup.Name}}, 
                      @{Name = 'Description'; Expression = {$adGroup.Description}}
    }
    else {
        Write-Warning "Group '$group' could not be found.."
    }
}

# now group the results on the GroupName property and 
# return objects with joined SamAccountNames and Descriptions
$results | Group-Object GroupName | ForEach-Object {
    [PsCustomObject]@{
        SamAccountName = ($_.Group.SamAccountName | Sort-Object -Unique) -join ', ' 
        GroupName = $_.Name
        Description = ($_.Group.Description | Sort-Object -Unique) -join ', ' 
    }
} | Export-Csv -Path 'C:\TEMP\GroupMemberShip.CSV' -NoTypeInformation 

虽然我不明白为什么你想在输出中有重复的项目,但你可以像下面那样做

$Groups = "Group1", "Group2", "Group3", "Group2", "Group3"
$results = foreach ($Group in $Groups) {
    $adGroup = Get-ADGroup $group -Properties Description -ErrorAction SilentlyContinue
    if ($adGroup) {
        $adGroup | Get-ADGroupMember -Server 'contoso.com' | 
        Select-Object @{Name = 'SamAccountName'; Expression = {($_.SamAccountName | Sort-Object -Unique) -join ', '}},
                      @{Name = 'GroupName'; Expression = {$adGroup.Name}}, 
                      @{Name = 'Description'; Expression = {$adGroup.Description}} -ExcludeProperty SamAccountName
    }
    else {
        Write-Warning "Group '$group' could not be found.."
    }
}

$results | Sort-Object GroupName | Export-Csv -Path 'C:\TEMP\GroupMemberShip.CSV' -NoTypeInformation