The purpose of this script is to enumerate all users that not belong to group names containing a specific pattern. The output shows samAccountName and email address.
The test of the attribute “$user.memberof” has been added because when this attribute is null, it means the user is only member of the built-in group “Domain Users”

Script (with Microsoft Active Directory module loaded : import-module activedirectory) :

$users = Get-ADUser -ResultSetSize $null -Properties SamAccountName,mail,memberof -LDAPFilter "(&(mail=*@company.com)(mail=*))"
foreach ($user in $users) {
	if ($user.memberof -ne $null) {
		if (($user |Select-String -NotMatch -inputobject {$_.memberof} -pattern "Group-Pattern-to-search") -ne $null) {
		write-host $user.SamAccountName "," $user.mail
		}
	}
	else {
		write-host $user.SamAccountName "," $user.mail
	}
}

Script (with Quest Active Directory module) :

$users = Get-QADUser -SizeLimit 0 -IncludedProperties SamAccountName,mail,memberof | where {($_.mail -ne $null) -and ($_.mail -like "*@company.com")}
foreach ($user in $users) {
	if ($user.memberof -ne $null) {
		if (($user |Select-String -NotMatch -inputobject {$_.memberof} -pattern "Group-Pattern-to-search") -ne $null) {
		write-host $user.SamAccountName "," $user.mail
		}
	}
	else {
		write-host $user.SamAccountName "," $user.mail
	}
}
Get users that not belong to similar group names

Leave a Reply

Your email address will not be published.