Wednesday, November 5, 2014

Powershell: Get AD Users from Group with Email Address

Here's a handy script I use to Generate a list of all "Users" with email addresses within a group. It's a recursive function so it will dig through nested groups to make sure all users are picked up. It does not do checking for duplicates as I normally just open the output in Excel and run the Remove Duplicates command.

### -----------------------------------------------------------------
### Written by Matt Brown
###
### Description: Get Username / Email from All Users in AD Group
###
### Requires: ActiveDirectory Module
### -----------------------------------------------------------------

Import-Module ActiveDirectory
$group = "Employees"
$outfile = ("c:\" + $group + "_output.csv")

function RecurseMyGroup($group,$outfile) {

 Write-Host ("Checking Group " + $group)
 (Get-ADGroup $group -properties members).members | foreach {
  $object = Get-ADObject $_ -Properties mail,samaccountname
  if($object.objectClass -eq "Group") {
   RecurseMyGroup $object.DistinguishedName $outfile
  } else {
   ($object.samaccountname + "," + $object.mail) | Out-File -FilePath $outfile -Append
  }
 }
 
}

RecurseMyGroup $group $outfile

No comments:

Post a Comment