Forum Discussion

StevenWatts's avatar
StevenWatts
Copper Contributor
Jan 24, 2023
Solved

Check user is in Security Group after being added by PowerShell script.

I have an issue whereby once the PS script attempts to add a user to the security group it will drop into the else statement on line 18. Regardless of whether the user was added into the security gro...
  • Harm_Veenstra's avatar
    Jan 24, 2023

    StevenWatts 

    Ran the script on my test Domain Controller. I don't think there's a need to specify the Domain Controller because you are running the adding of the user and the query if it's in the group in the same connection. But...

     

    You gather all the members in the $members variable. Then you test if the user is part of the group. If it isn't, then you add it to the group. And then you check the same $members variable again, which isn't updated with the user being in it 🙂 And that's why it reports it as not added to the group. You should add the $members= get-adgroupmember... on line 14 again to verify if the user has been added to the group.

     

    When adding the user to the group, the script below with a try/catch will check if that succeeds. If it fails, it will report that on screen. If it works, it will tell you without rechecking the group. (Trust your AD 😉 )

     

    # Get the user and group information
    $user = Get-ADUser $UserName 
    $group = Get-ADGroup $GroupName
    $members = Get-ADGroupMember -Identity $GroupName -Recursive | Select-Object -ExpandProperty distinguishedName
    
    # Check group membership
    
    If ($members -contains $user) {
        Write-Host("User {0} already (indirect) member of group {1}" -f $user.UserPrincipalName , $group.Name) -ForegroundColor Green
    }
    Else {
        try {
            Set-ADObject -identity $group -add @{member = $user.DistinguishedName } -ErrorAction Stop
            Write-Host("User {0} successfully added to group {1}" -f $user.UserPrincipalName , $group.Name) -ForegroundColor Green
        }
        catch {
            Write-Warning ("Error adding {0} to {1}, check the name of the group and/or permissions" -f $user.UserPrincipalName , $group.Name)
        }				  
    }  

Resources