Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining PowerShell Get-ADUser Filters

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading