Exclude security groups from Get-ADUser

I’m new to Powershell and I’m trying to use Powershell to generate a list of inactive user accounts. I have been able to get this to work with some research and borrowing code from others. I now have a need to exclude specific security groups from the results. I attempted to use the -LDAPFilter parameter but this cause a pipeline error. Is it possible to do this in Powershell and what would be the best approach?

Search-ADAccount -UsersOnly -AccountInactive -DateTime “10/05/2011” -ResultPageSize 2000 -ResultSetSize $null -SearchBase “targetOU” -SearchScope Subtree -Server serverFQDN|Get-ADUser -Properties * -LDAPFilter "(&(&(objectCategory=User))(!(memberOfDNofsecuritygroup)))"| Select DisplayName,SamAccountName,
@{n=“LastLogonTimeStamp”;
e={[DateTime]::FromFileTime($.lastlogon)}},`
@{name=‘MemberOf’; expression={ ($
.MemberOf | ForEach { ($_ -split ‘,’)[0] -replace ‘CN=’,‘’}) -join ‘,’}}| Export-Csv c:\results.txt

Well, it depends on the error you got of course - please always include errors - but I don’t think you can specifically do what you’re looking for in a single command.

I don’t think AD actually tracks what groups a user belongs to as an attribute of the user object, so there’s no way Get-ADUser can filter on that. Group membership is tracked as part of the Group object. So as far as I know, you’d have to get all the users, and then get the members of the group, and then filter (in PowerShell, using Where perhaps) out the ones you don’t want. In other words, I don’t think the domain controller will do all that for you in a single operation.

Here is the error, but thanks for the assistance. I will try using Where.

Get-ADUser : The input object cannot be bound to any parameters for the command either because the
command does not take pipeline input or the input and its properties do not match any of the parameters
that take pipeline input.
At .ps1:5 char:24

  • Where {$_.Enabled } | Get-ADUser -Properties * -LDAPFilter "(&(&(objectCategory …

I think you can do this using Get-ADUser and the -Filter parameter. See if this works:

$ExemptGroup = Get-ADGroup “Group Name Goes Here” # Fill this in and make sure it successfully finds the group
$InactiveDate = (Get-Date).AddDays(-30) # Or put a datetime object here if you’re looking for a specific date
Get-ADUser -Filter { -not (memberOf -RecursiveMatch $ExemptGroup.DistinguishedName) -and (LastLogon -lt $InactiveDate) -and (Enabled -eq $true) } -Properties LastLogonDate, DisplayName |
select DisplayName, SamAccountName, LastLogonDate

For more examples of using the filter parameter, check out the about_ActiveDirectory_Filter help topic.