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'
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