0

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?

0

2 Answers 2

1

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 $_ }
Sign up to request clarification or add additional context in comments.

1 Comment

Hi theo,thanks for your answer works perfectly and can see where I was going wrong now. Thanks to everyone else who contributed too
1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.