Check if user exists in group

Viewed 2405

I cant get this script to give the right output, I want to check if a user (from the Users.csv) exists in a group (there is one group in each domain, this is a multi domain environment).

I think the problem lies in the second foreach. Right now the output is the right numbers of lines for each domain, but they all say :

aa@aa.aa bb@bb.bb does not exists in the group PSO_StdPasswordPolicyWithNoAccountLockout

Where it should say:

aa@aa.aa does not exists in the group PSO_StdPasswordPolicyWithNoAccountLockout

bb@bb.bb does not exists in the group PSO_StdPasswordPolicyWithNoAccountLockout

Users.csv contains EmailAddress, DisplayName, objectGUID

Clear-Host

$user = Import-Csv ".\Users.csv" 
$group = "PSO_StdPasswordPolicyWithNoAccountLockout"

$domains = (Get-ADForest).domains

foreach ($domain in $domains) {

    Write-Host ="********** - $domain - **********" -ForegroundColor Yellow

    $members = Get-ADGroupMember -Identity $group -Server $domain | Select-Object objectGUID
    $exportMembers = $members | Export-Csv .\RemoveUsersTemp\$domain.csv -NoTypeInformation
    $importFile = ".\RemoveUsersTemp\$domain.csv"
    $amembers = import-csv $importFile | Select-Object objectGUID

    foreach ($amember in $amembers) {
        If ($amembers.objectGUID -contains $user.objectGUID) {
            Write-Host $user.EmailAddress"exists in the group $group " -ForegroundColor Green
        }
        Else {
            Write-Host $user.EmailAddress"does not exists in the group $group" -ForegroundColor Red
        }
    }

}
1 Answers

This is because you use $user in the second loop, but you're not looping $user, so you're referring the whole $user array, which has the content of users.csv.

Related