Powershell to add users to a group

directorygroupspowershell

I have written this bit of PS to add users from a text file to and AD group that the user inputs. It works fine except for the if statement. The if statement is supposed to check the group to see if the users in the text file are already group members.
So, the $item variable gets initialized with 'jdoe' and the $member variable gets initialized as so:

$member=Get-ADGroupMember -identity $group | select SamAccountName

The problem member will get initialized with @{SamAccountName=JDoe}, @{SamAccountName=bsmith}, etc. Basically, all the members in one foul swoop and encapsulated with the additional data thus obscuring the data used for the comparison.
Here is my code in it's entirety. I would appreciate any help. Thanks

#User input group name
$group=read-host -prompt "Enter group name:"

#Loop through each item in text file
foreach ($item in Get-Content C:\addusers.txt) {
    #If user is already a member of group...
    $member = Get-ADGroupMember -identity $group | select SamAccountName
    if ($member -eq $item) {
         Write-Host $item "is already a member of" $group
    }

    #add to group
    Add-ADGroupMember -Identity $group -Member $item
}

Best Answer

The first problem is your comparison. The line that assigns a value to $member returns a list, not a single item. So you are basically asking in the test "if this big list is equal to a single item." That condition will never be true, except perhaps is the group has only one member (I am not sure if you will get a single item in that case, or an array object with one member).

Second issue is that you don't do anything with this test's results--you still run the group addition even if the user is already in the group (assuming your test was written correctly). Why?

It also has a lot of overhead, as it will run this dump of the group's contents each time you run it. Better would be to get the group members once, outside of your foreach loop, and then use an array search on that list inside the foreach loop. That's less of a concern, but may be worth fixing.

PS--you can add a user to a group even if they are already a member of the group. So you may want to remove this comparison altogether:

foreach ($user in get-content $userspath) {
    Add-ADGroupMember -Identity $group -Member $user
}

Edit: If you still want to search for the existence of a member in the group, you could do it like this:

$u = get-aduser $user -properties "memberof"
if ($u.memberOf -contains (get-adgroup $group) ) 
    ...