robert glass
robert glass

Reputation: 3

powershell script to add users to group if not a member of another group

I have an issue with the following script:

get-aduser -filter * -searchbase "dc=domain,dc=global" -ResultSetSize $null | where-object {((get-aduser $_.samaccountname -properties memberof).memberof -ne "Mimecast Remote Access Exceptions")} | ForEach {add-adgroupmember -identity "Mimecast Internal Access" -member $_.samaccountname}

It is still adding all users but not filtering out users who are members of the remote access exceptions group. Any idea what I am doing wrong?

Upvotes: 0

Views: 1714

Answers (2)

Steven
Steven

Reputation: 7057

Building on @Theo's Answer

.memberOf will return distinguished name strings. -notcontains won't work unless you change the left hand side to the DN. That might look something like:

$DN = 'CN=Mimecast Remote Access Exceptions,OU=SomeOU,DC=domain,DC=global'

Get-ADUser -Filter * -SearchBase "dc=domain,dc=global" -Properties MemberOf | 
Where-Object {$_.MemberOf -notcontains $DN } | 
ForEach-Object { Add-ADGroupMember -Identity $DN -Members $_ }

Obviously correct $DN for your environment etc...

Upvotes: 1

Theo
Theo

Reputation: 61068

First of all, you don't need to perform Get-ADUser twice.
Then, the MemberOf user property is a collection, not a single string, so you need to use -notcontains instead of -ne

Try:

# get the DistinguishedName property of the group
$groupDN = (Get-ADGroup -Identity "Mimecast Remote Access Exceptions").DistinguishedName
Get-ADUser -Filter * -SearchBase "dc=domain,dc=global" -Properties MemberOf | 
Where-Object {$_.MemberOf -notcontains $groupDN} | 
ForEach-Object { Add-ADGroupMember -Identity "Mimecast Internal Access" -Members $_ }

Upvotes: 1

Related Questions