I have script that will search within an OU and display username, names, AD group and description.
$ou = 'distinguishedName of the 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\MyUsername\Desktop\NameOfMyFile.csv -NoTypeInformation
Going off research I believe I have to use Get-ADUser and mail attribute.
Something like:
($members in Get-ADUser $1)
Email = $1.mail
I have tried to alter this code and failed miserably.
Please could anyone assist?
If you're looking for just user object membership, instead of using Get-ADGroupMember
you can use Get-ADUser
querying for "users which's MemberOf
attribute is equal to the group's DistinguishedName
":
$ou = 'distinguishedName of the OU'
Get-ADGroup -Filter * -SearchBase $ou -Properties Description | ForEach-Object {
$params = @{
LDAPFilter = '(memberof={0})' -f $_.DistinguishedName
Properties = 'mail'
}
foreach($member in Get-ADUser @params) {
[pscustomobject]@{
SamAccountName = $member.SamAccountName
Name = $member.Name
Mail = $member.Mail
GroupName = $_.Name
Description = $_.Description
}
}
} | Export-csv C:\Users\MyUsername\Desktop\NameOfMyFile.csv -NoTypeInformation