简体   繁体   中英

Filtering out letters when using get-aduser not working in powershell

I am trying to filter out letters in listing out usernames by using get-aduser. I get an error saying a parameter cannot be found that matches parameter name "filter".

Get-ADUser -Filter * |? { $_.samaccountname -match '^[a-j][A-J]' }

I would recommend building an LDAP filter for sAMAccountName that meets your requirements, rather than filtering after the fact with Where-Object . Example:

$charRange = ([Char] 'a'..[Char] 'j') | ForEach-Object { [Char] $_ }
$ldapFilter = "(&"
$charRange | ForEach-Object { $ldapFilter += "(!sAMAccountName=$_*)" }
$ldapFilter += ")"
Get-ADUser -LDAPFilter $ldapFilter

Basically this builds an LDAP filter that means " sAMAccountName that does not start with any of the characters a through j ".

If you instead want to include only user accounts where the sAMAccountName attribute starts with the letters a through c , you would use this instead:

$charRange = ([Char] 'a'..[Char] 'c') | ForEach-Object { [Char] $_ }
$ldapFilter = "(|"
$charRange | ForEach-Object { $ldapFilter += "(sAMAccountName=$_*)" }
$ldapFilter += ")"
Get-ADUser -LDAPFilter $ldapFilter

Note that the & in the LDAP query is changed to | and the ! is removed. This LDAP filter means " sAMAccountName that starts with any of the characters a through c ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM