导出 Active Directory 中用户的组和用户名

Export groups and username of a user in Active Directory

我正在尝试找出所有 active 用户所在的 Active Directory 组,并希望将其导出到 CSV 文件。但是,以下命令在相关 CSV 文件中显示垃圾。

这是我的代码失败:

Import-Module ActiveDirectory
Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter * |  where { $_.enabled -eq "true" } | foreach-object {
    write-host "User:" $_.Name 
    Get-ADPrincipalGroupMembership $_.SamAccountName | foreach-object {
        write-host "Member of:" $_.name | export-csv "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8
    }
}

知道我做错了什么吗?

Write-Host 仅将文本写入控制台 window。它不会输出任何有用的东西来传递给 Export-Csv.
此外,除非您添加开关 -Append,否则您应该将 Export-Csv cmdlet 设置为代码的最后一行,否则您将在每次迭代中覆盖它。

尝试

Select-Object

Import-Module ActiveDirectory
Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter "Enabled -eq $true" | 
Select-Object Name, @{Name = 'Groups'; Expression = {($_ | Get-ADPrincipalGroupMembership).Name -join '; '}} |
Export-Csv -Path "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8

ForEach-Object

Import-Module ActiveDirectory
$result = Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter "Enabled -eq $true" | 
ForEach-Object {
    [PsCustomObject]@{
        Name = $_.Name
        Groups = ($_ | Get-ADPrincipalGroupMembership).Name -join '; '
    }
}
$result | Export-Csv -Path "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8