0

Currently I have a script that I am able to interrogate an OU (which I define in the script) which shows Username, Name of the user, AD Group Name and the Description of that AD group into a CSV file:

$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

When I try to pull of the email addresses of the users as well in the same script I get an error.

$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

The error message states the script fails around this point of the script:

-Properties 'Description', 'EmailAddress'
S.Mahmood
  • 129
  • 11

2 Answers2

1

The LDAP Display Name for the E-mail-Address attribute in Active Directory is not EmailAddress, but mail:

Get-ADGroup -Filter * -SearchBase $ou -Properties 'Description', 'mail' | ...
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Tried this, it ran but didn't get the email addresses seems in the CSV. – S.Mahmood Feb 22 '23 at 18:41
  • 1
    @S.Mahmood Well, you'd need to replace the references to `EmailAddress` throughout the script, including `EmailAddress = $user.EmailAddress` -> `EmailAddress = $user.mail` – Mathias R. Jessen Feb 22 '23 at 18:44
1

If you want to include the email addresses of the users you will need to take it one step further and call Get-ADUser foreach member in the group.
Snag is that Get-ADGroupMember can return not only users, but computer ad group objects as well, so you will need to filter those out.

$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
Theo
  • 57,719
  • 8
  • 24
  • 41