通过Get-ADGroup命令在Powershell中检索CSV文件中的电子邮件地址

uinbv5nw  于 2023-03-12  发布在  Shell
关注(0)|答案(2)|浏览(141)

目前,我有一个脚本,我可以询问OU(我在脚本中定义),该OU将用户名、用户名、AD组名称和该AD组的描述显示到CSV文件中:

$ou = 'distinguishedName of my OU'
Get-ADGroup -Filter * -SearchBase $ou -Properties Description | ForEach-Object {
    foreach($member in Get-ADGroupMember $_) {
        [pscustomobject]@{
            SamAccountName = $member.SamAccountName
            Name           = $member.Name
            GroupName      = $_.Name
            Description    = $_.Description
        }
    }
} | Export-csv C:\Users\Me\Desktop\MyFile.csv -NoTypeInformation

当我尝试在同一个脚本中提取用户的电子邮件地址时,我得到了一个错误。

$ou = 'distinguishedName of my OU'
Get-ADGroup -Filter * -SearchBase $ou -Properties 'Description', 'EmailAddress' | ForEach-Object {
    foreach($member in Get-ADGroupMember $_)  
    {
        [pscustomobject]@{
            SamAccountName = $member.SamAccountName
            Name           = $member.Name
            EmailAddress   = $_.EmailAddress
            GroupName      = $_.Name
            Description    = $_.Description
        }
    }
} | Export-csv C:\Users\Me\Desktop\MyFile.csv -NoTypeInformation

错误消息指出,脚本在此点附近失败:

-Properties 'Description', 'EmailAddress'
oipij1gg

oipij1gg1#

如果您希望包括用户的电子邮件地址,则需要更进一步,为组中的每个成员呼叫Get-ADUser
问题是Get-ADGroupMember不仅可以返回用户,还可以返回计算机广告组对象,所以您需要过滤掉这些对象。

$ou = 'distinguishedName of my OU'
Get-ADGroup -Filter * -SearchBase $ou -Properties 'Description' | ForEach-Object {
    $group   = $_  # just for convenience..
    $members = Get-ADGroupMember $_ | Where-Object { $_.objectClass -eq 'user' }
    foreach($member in $members) {
        $user = Get-ADUser $member -Properties EmailAddress
        [pscustomobject]@{
            SamAccountName = $user.SamAccountName
            Name           = $user.Name
            EmailAddress   = $user.EmailAddress
            GroupName      = $group.Name
            Description    = $group.Description
        }
    }
} | Export-csv C:\Users\Me\Desktop\MyFile.csv -NoTypeInformation
thtygnil

thtygnil2#

the E-mail-Address attribute in Active Directory的LDAP显示名称不是EmailAddress,而是mail

Get-ADGroup -Filter * -SearchBase $ou -Properties 'Description', 'mail' | ...

相关问题