0

I have been troubleshooting code today and I discovered that this code does not work. I am using a PowerShell pipeline to send an array of distinguished names to search Active Directory for users with a manager.

$managers | Get-ADUser -Filter {manager -eq $_}

However, if I expand the command to this example with a foreach-object loop and an explicit variable, the code does work.

$managers | %{$manager = $_; Get-ADUser -Filter {manager -eq $manager}}

What part of the source code forces users to write out expressions like this?

I'm not familiar with the source code for Get-ADUser, but in working with native PSCustomObjects, using the pipeline works as expected in the first example.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
qwe57boz8
  • 33
  • 5
  • What do you expect to be in $_? Now think about why that isn't the case. Try this: `$managers | ForEach-Object { Get-ADUser -Filter {manager -eq $_}}` – Scepticalist Mar 10 '23 at 16:36
  • -filter Accept pipeline input: False, granted it's unusual – js2010 Mar 10 '23 at 17:11

1 Answers1

3

Short answer is -Filter does not take pipeline input hence no delay-bind script block is possible. And there is a good reason for this, the filter used needs to be passed as is to the Filter Provider, cannot be evaluated beforehand.

As a minimal example, try this function which's -Filter parameter takes ValueFromPipeline and then remove the ValueFromPipeline.

function Get-ADThing {
    param(
        [Parameter(ValueFromPipeline)]
        [string] $Filter
    )

    process {
        $Filter
    }
}

'foo', 'bar', 'baz' | Get-ADThing -Filter { "name -eq $_" }
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37