Author Posts

May 16, 2018 at 9:50 pm

Get-ADOrganizationalUnit -Filter {Name -ne "FilteredOutOU"} -SearchBase "OU=FilteredOutOU,DC=domain,DC=local" | Get-ADUser -Filter * -SearchBase "OU=FilteredOutOU,DC=domain,DC=local"

I would expect this to not produce any output, but it displays all users in the very OU I don't want to query.

Thanks,
Craig

May 16, 2018 at 10:52 pm

You're not passing anything to the Get-ADUser command from the pipeline, so it will return on the Get-ADUser filter since you're not passing anything to Get-ADUser.

If there was a sub-OU on your filtered OU, you'd receive an error:

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.

May 16, 2018 at 10:56 pm

Your "Get-ADUser" works independend of the cmdlet before the pipe. You specified everything it needs to work properly. What do you want to achive with this code? If you like to limit the OUs the cmdlet searches in you will have to use a loop and reference the pipeline object ... something like this:

Get-ADOrganizationalUnit -Filter {Name -ne "FilteredOutOU"} -SearchBase "OU=FilteredOutOU,DC=domain,DC=local" | 
    ForEach-Object{
        Get-ADUser -Filter * -SearchBase $_.DistinguishedName
    }

.... !!!! but because you're specifying the -SearchBase as the OU you like to limit to you will not get any result. You should change the -SearchBase to something "higher" in the tree. 😉

May 17, 2018 at 6:10 pm

Thank you all. I understand what you're saying, but I'm not having luck putting it into practice. I ended up doing this:

Get-ADOrganizationalUnit -Filter * -SearchBase "DN" -SearchScope Base | Select-Object -ExpandProperty DistinguishedName | `
        ForEach-Object {
                Get-ADUser -Filter * -SearchBase $_ | Where-Object {($_.DistinguishedName -notlike "*FilteredOutOU*")}
        }

May 17, 2018 at 9:54 pm

Please try to avoid backticks. They are ugly, hard to see (a lot of us are not 22 anymore 😉 😎 ), error prone and most of the time unnecessary. Especially when you have a pipe symbol direct in front of it. Line breaks are allowed after commata, semicola, opening parenthesis or curly braces AND pipe symbols!! 😉
I think you can even shorten this a bit more. Try this:

Get-ADOrganizationalUnit -Filter "Name -ne 'FilteredOutOU'" -SearchBase 'DN' -SearchScope Base | 
    ForEach-Object{
        Get-ADUser -Filter * -SearchBase $_.DistinguishedName
    }