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.
>Solution :
Don’t filter with powershell when active-directory 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.