Reputation: 25
I've created a script that lists all users in a OU that are NOT a member of a certain group. This saves the results into a text file. I thought this was working fine until I took a username from the text file and searched it in Active Directory. Turned out the user was a member of the group I was trying to filter out. Here is the code -
Get-ADUser -SearchBase "OU=Users 2004,OU=Cyngor,DC=gwynedd,DC=rhwydwaith" -Filter {( memberof -ne "CN=CTX AppSense,OU=Rheoli,OU=Grwpiau,OU=TC Enviroment,DC=gwynedd,DC=rhwydwaith")} -Properties Name | select Name | Export-CSV "C:\Users.txt"
I can't figure out why this isn't working correctly. Any suggestions out there?
Thanks.
Upvotes: 0
Views: 280
Reputation: 200493
memberOf
is a multi-valued attribute, i.e. a list of distinguished names. Use the -notcontains
operator to check if does not contain a particular distinguished name:
$ou = 'OU=Users 2004,OU=Cyngor,DC=gwynedd,DC=rhwydwaith'
$dn = 'CN=CTX AppSense,OU=Rheoli,OU=Grwpiau,OU=TC Enviroment,DC=gwynedd,DC=rhwydwaith'
Get-ADUser -Filter * -SearchBase $ou -Properties Name, MemberOf |
? { $_.MemberOf -notcontains $dn } |
select Name |
Export-Csv 'C:\Users.txt' -NoType
Note that a user's primary group is not listed in the memberOf
attribute. If the code should also handle primary groups you need to add a check for that:
$ou = 'OU=Users 2004,OU=Cyngor,DC=gwynedd,DC=rhwydwaith'
$dn = 'CN=CTX AppSense,OU=Rheoli,OU=Grwpiau,OU=TC Enviroment,DC=gwynedd,DC=rhwydwaith'
Get-ADUser -Filter * -SearchBase $ou -Properties Name, MemberOf |
? { $_.MemberOf -notcontains $dn -and $_.PrimaryGroup -ne $dn } |
select Name |
Export-Csv 'C:\Users.txt' -NoType
Upvotes: 1