Martin
Martin

Reputation: 535

ForEach-Object in Pipeline Not Working

Could someone explain to me why the following works

$Users = 'First1 Last1','First2 Last2','First3 Last3'

foreach ($User in $Users)
{
    (Get-ADUser -Filter *).Where{$_.Name -like "*$User*"}
}

but this does not

$Users | % { (Get-ADUser -Filter *).Where{$_.Name -like "*$_*"} }

I feel like it's essentially the exact same thing but the first commands return data while the second does not

Upvotes: 1

Views: 677

Answers (2)

Angel Abad Cerdeira
Angel Abad Cerdeira

Reputation: 1437

In the second loop variable $_ starts being the first user of $Users array, but it is overridden by the output of Get-ADUser.

In other words in the second loop in {$_.Name -like "*$_*"} the *$_* you think it is equivalent to $User it is not.

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

It's not the same thing, because .Where{$_.Name -like "*$_*"} uses the current object variable twice. In $_.Name it should refer to the current object from Get-ADUser, whereas in "*$_*" it should refer to the current string from $Users, but actually also refers to the current object from Get-ADUser.

Something like this would make the two statements the same:

$Users | % { $u = $_; (Get-ADUser -Filter *).Where{$_.Name -like "*$u*"} }

Upvotes: 1

Related Questions