Search code examples
powershellactive-directorypipeline

Piping output of get-ADUser to Get-ADGroup with an LDAP filter


I'm trying to stitch together two lines of PowerShell, but I just can't figure the syntax. There is a post that sounds like it might be what I need, but it isn't using -LDAPFilter.

To generate a list of AD users created in the last 100 days, I use

$now = ((Get-Date).AddDays(-100)).Date
$users = Get-ADUser -Filter {whenCreated -ge $now} -Searchbase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" |
         Where-Object { $_.Enabled -eq 'True' }

And this code from "How to get ALL AD user groups (recursively) with Powershell or other tools?" does the next step, which is to find all the groups that a user is a member of:

$username = 'd.trump'
$dn = (Get-ADUser $username).DistinguishedName
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) |
    select -Expand Name 

but I can't pipe the output of the first into the second to get an overall list.

Get-ADUser -Filter {whenCreated -ge $now} -Searchbase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" |
    Where-Object { $_.Enabled -eq 'True' } |
    Select-Object DistinguishedName |
    Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_) |
    select -expand Name

The error message is:

Get-ADGroup : The search filter cannot be recognized

I thought the second code snippet extracted the distingushed name and supplied it to the filter, and that is what I have tried to do in the pipeline.


Solution

  • You are missing ForEach-Object (alias %).

    The following code should work:

    Get-ADUser -Filter {whenCreated -ge $now} -SearchBase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" `
    | Where-Object { $_.Enabled -eq 'True' } `
    | %{Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_.DistinguishedName)} `
    | Select-Object -ExpandProperty Name
    

    If you want to output both user and group information you can expand the code like this:

    Get-ADUser -Filter {whenCreated -ge $now} -SearchBase "OU=staff,OU=SMUC_Users,DC=stmarys,DC=ac,DC=ie" `
    | Where-Object { $_.Enabled -eq 'True' } `
    | %{$group = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $_.DistinguishedName);Write-Output $_.UserPrincipalName $group.Name}