Combining PowerShell Get-ADUser Filters

195 Views Asked by At

Good afternoon, all.

I am trying to perform a search in P/S for SamAccountName that contains / starts with "svc_", and does not belong to a group called "disconnected", and write that to an Excel file.

What I am trying, at least for the syntax, doesn't result in anything. I know there are 300+ accounts that should show.

What am I declaring wrong?

get-aduser -filter * -properties *|? {$_.samaccountname -like "svc_" -and $_.MemberOf -eq "disconnected"}

I am also looking to do the same for those SamAccountName results that are not part of a group. I thought "-neq" would work (not equal), but I guess that value is wrong?

get-aduser -filter * -properties *|? {$_.samaccountname -like "svc_" -and $_.MemberOf -neq "disconnected"}

Once my mistakes are figured out, I will add | Export-Csv -Path $CSVfile -NoTypeInformation to have it write to a csv file.

Thank you in advance for all the assistance.

1

There are 1 best solutions below

7
Santiago Squarzon On BEST ANSWER

Don't filter with when can do it for you, its many times more efficient that way:

$groupdn = (Get-ADGroup disconnected).DistinguishedName

# members of the group and start with `svc_`
Get-ADUser -LDAPFilter "(&(samAccountName=svc_*)(memberOf=$groupdn))" |
   Export-Csv path\to\membersofgroup.csv -NoTypeInformation

# not a member of the group and start with `svc_`
Get-ADUser -LDAPFilter "(&(samAccountName=svc_*)(!memberOf=$groupdn))" |
   Export-Csv path\to\notmembersofgroup.csv -NoTypeInformation

As for the problem with your current code:

$_.samaccountname -like "svc_"

Should use a wildcard after svc_:

$_.samaccountname -like "svc_*"

And:

$_.MemberOf -eq "disconnected"

Will never match since MemberOf is a collection of DistinguishedName.


Notes:

  • The above code only looks for user objects, if you need to find members of mentioned group of any objectClass, then you can change Get-ADUser to Get-ADObject.

  • This code only looks for direct members of the mentioned group, if you need to find the recursive members you can use a LDAP_MATCHING_RULE_IN_CHAIN. For this the filter would look like:

# recursive member of group
"(&(samAccountName=svc_*)(memberOf:1.2.840.113556.1.4.1941:=$groupdn))"

# not a member of the group or any nested group
"(&(samAccountName=svc_*)(!memberOf:1.2.840.113556.1.4.1941:=$groupdn))"