2021 Jun 13
Check Users with No Groups by Pattern
11:29 - By Andrii Dykhlin - ActiveDirectory - Permalink
Imagine the situation when someone (probably, from Audit) comes to you and asks to provide the list of users (if any) without a particular group (or groups by imaginary pattern). It could happen, so you need to be more or less prepared.
In this case you can use the script like below. It uses the group membership to distinguish users from service accounts, or accounts used for meeting rooms, or on some sort of dashboards, monitoring machines etc., you can also specify by different attributes in AD, for example, you can use employeeID, especially if it is used to sync to Azure AD. It might also help, if you want to find users that are synced to AAD, but don't have the password policy applied (we are using the password policy group in the example).
<#
This is a script to check the users that are not a part of a group with a matching criteria (specified on Line 12).
Will return a list of the users, the output could be expanded if needed
#>
$results = @()
$users = Get-ADUser -Properties memberof -Filter {enabled -eq $True} | ? {$_.memberof -like "*PasswordPolicyUsers*"}
foreach ($user in $users) {
$groups = $user.memberof -join ';'
$results += New-Object psObject -Property @{'User'=$user.name;'Groups'= $groups}
}
$results | Where-Object { $_.groups -notmatch 'SRP' } | Select-Object User | Sort-Object User
We create a few variables: $results is used to create an empty array, $users will create a set of users with the criteria as of being enabled, and a member of the group PasswordPolicyUsers. The ? is the alias for Where-Object.
After that we are going through the loop, and check each entry from the users output one by one, creating for each user the variable $groups, that will join all the groups togeter with a semicolon to one string. With the next line you create a table of users and their groups. All the groups are in the distinguished name format, so like CN=Group,OU=Security Groups,DC=domain,DC=local
Last line will just show the list of the users without the matching. In this case is "SRP", but it could be anything. You will have a list of names, so you can go and check why there is no such group for them,