Using PowerShell to find all groups with members in a different domain

Yesterday I was asked by the Security Team to help them out with a project they were working on.  There is an OU with over 2,000 groups in it and they needed to find the names of all the groups whose members where in a different domain. 

#This script requires the Microsoft 'ActiveDirectory' module to be loaded.  
#The module is part of the Win7 RSAT and comes standard on Server 2008 R2
$Erroractionpreference = "SilentlyContinue" # For whatever reason, there are groups that can't be bound to.  
											# I will guess these are orphaned. In either case this line prevents errors from being displayed
foreach ($group in Get-ADGroup -SearchBase 'OU=SOMETHING,OU=GROUPS,OU=SOMETHING,OU=BUSINESSUNIT,DC=EmptyGarden,DC=info' -Filter *)
	{
	foreach ($user in Get-ADGroupMember -Identity $Group.Name)
		{
		if ($user.distinguishedName -notlike '*AnotherDomain,*') 
			{
			$group.name
			break # We only care if one user is a member of a different domain.  Thus, once we find one, we get out of the IF loop and grab another group.
			}
		}
	}

Leave a Reply

Your email address will not be published. Required fields are marked *