Script to see if a list of users are in list of groups
11:04 19 May 2025

I have a list of users that i get every week that have termed. I need to cross check these users to see if they are a member of a specific list of groups that are name with a pattern like "ABC_*" (we have hundreds of these that is why the wildcard). i have the following script and made some changes to it...

The csv file has no header. The attribute i have listed in the file is "samAccountName" like: JThapa Hsmith RJoy MWhite

$users = Get-Content "C:\PS\Input\PSWeeklyterms.csv" # Path to the 
file containing the list of users (one user per line)
$groupName = Get-ADGroup -Filter {Name -like "APP_*"} # Replace 
with the actual group name

foreach ($user in $users) {
$isMember = Get-ADPrincipalGroupMembership $user | Where-Object 
{$_.Name -eq $groupName}
if ($isMember) {
    Write-Host "$user is a member of $groupName"
} else {
    Write-Host "$user is not a member of $groupName"
}
}

 $table | Export-Csv "C:\PS\Output\PSWeeklyTerms_Results.csv" -NoTypeInformation

The issue i am facing is it returns with some results but also an error below.

    Get-ADPrincipalGroupMembership : An unspecified error has occurred
    At line:5 char:17
    +     $isMember = Get-ADPrincipalGroupMembership $user | Where- 
     Object { ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (RThapa:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership

It displays the DN of the group the user is not a member of. It also doesn't export the data... the file is empty with 2 random characters.

powershell active-directory group-membership