Using MS PowerShell script to generate CSV of Exchange users and groups?

scottmso

Limp Gawd
Joined
Apr 15, 2004
Messages
380
Hey all!

I need to generate a CSV file that contains a list of Exchange users (email addresses) and the distribution groups that they are members of. Apparently you can generate a CSV file with a whole bunch of information about your Exchange users, but not the groups that they are members of.

I have code (below) that works. However, its method of operation is very inefficient (for each user, go through the list of every group and see if the user is present). Therefore, it takes about 30 seconds per user, and the organization has approximately 10K users in its mailing lists...meaning it will take several days for it to complete. There has to be a better way to do this, but I can't figure it out...I have no previous experience with Exchange or Powershell and have basically been figuring this out as I go along.

The way I would like to do it would be to start with a list of email addresses of all users in the Exchange server (easily obtainable), then go through the list of members of the distribution groups (easily done) and append ",(NAME OF GROUP)" to the line where the given email address is. I can figure out how to get the line number on which a string (in this case, email address) is located, but cannot figure out how to append text to a particular line using Powershell.

Any advice on how I might be able to go about this would be greatly appreciated. Thanks!

Code:
$fileloc = Read-Host "Please type the path where the file should be saved" # prompt user for file location
"Emailaddress,Group1,Group2,Group3,Group4,Group5" | out-file $fileloc; # print "header"

$i = 0; # counter

get-contact -resultsize unlimited | foreach { 
	$ct = $_; # get contact info
	$str = $ct.WindowsEmailAddress.ToString(); # add username to beginning of str to be printed
	Get-DistributionGroup | foreach {
		$dg = $_; # get dist group info
		get-distributiongroupmember $dg | foreach {
			if ($_.identity -like $ct.identity) 
			{
			$str = $str + "," + $dg.toString();
			} 
		}
	}

	$t = Get-Date; # time
	$i = $i + 1; # update counter
	$t.ToShortTimeString() + " " + $i.toString() + " users complete"; # display counter

	$str | out-file $fileloc -append; # print string
}
 
Back
Top