'Check if users are a member of an AD group - Powershell

i have a txt file with a list of usernames and I want to check if these users are a member of a specific AD-group. If they aren't a member of this group, their username has to be written in a csv file. So the output should be a csv file with all usernames who are not in the specified AD-group.

I always get the error "A connection to the directory on which to process the request was unavailable. This is likely a transient condition".The error is reproduced when implementing a workflow that triggers up to 20 powershell sessions to run, each importing the Active Directory module to create a connection with AD.

This is my short script:

 $userlist = get-content -Path "C:\Temp\users.txt"

 $group = "group_xy"


 $result = foreach ($user in $userlist)
 {
     $groupmembers = Get-ADgroup -Filter {Name -eq $group}|Get-ADGroupMember 

     if ($groupmembers.samaccountname -notmatch $users){
        [PSCustomObject]@{
        Name = $user 
        Group = $group 
        Member = 'False'
        }
    }
    
}

$result |Export-csv "C:\Temp\Result.csv" -NoTypeInformation

How can I solve this?

BR



Solution 1:[1]

if ($groupmembers.samaccountname -notmatch $users) {

Should be

if ($groupmembers.samaccountname -notmatch $user) {

Since you never define $users I think this is the error

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P