Reputation: 37
Heyho, for a little script I'm making I have a huge list of users that I get from the active directory, for example by:
$userlist = Get-ADUser -Filter *
I've already narrowed it down to the search only the folder that I want it to search.. but there are still some "corpses" in there, some dead accounts that don't need to be in the list, but that also can't be deleted from the domain. How can I filter these accounts out of the list? Here are the fields that each user has in my list: screenshot of the output from Get-ADUser
If possible I'd like to filter out a list of names that are in another text file that I put into a variable. (I'd like to filter it by the "Name" field)
I've tried things along the line of:
$userlist = Get-AdUser -Filter 'Name -notin $Filter'
but that doesn't seem to work :( I managed to do it with a single keyword, but can't get it done with a list
$userlist = Get-ADUser -Filter 'Name -notlike "*test*"'
Thanks for the help!
Upvotes: 1
Views: 1289
Reputation: 60045
Active Directory Filter doesn't support the -notin
operator. You can use the following LDAP Filter trick to exclude those users from your query:
# $toExclude could be also pulled from a file, however you need to make
# sure there are no trailling or leading spaces on each line,
# you can use `.Trim()` for that.
#
# $toExclude = (Get-Content userstoexclude.txt).ForEach('Trim')
$toExclude = 'user.example1', 'user.example2', 'user.example3'
$filter = '(&(!name={0}))' -f ($toExclude -join ')(!name=')
# LDAP Filter would look like this:
# (&(!name=user.example1)(!name=user.example2)(!name=user.example3))
$userList = Get-ADUser -LDAPFilter $filter
If you're interested in learning more about LDAP Syntax for your queries you might want to check out:
Upvotes: 1