Learning about the pipeline

Hi everybody

Here is my novice question :slight_smile:

Why does this work
get-aduser -SearchBase ‘OU=SomeUserOU,DC=Company,DC=com’ -Filter * | Write-Output
and this
get-aduser -SearchBase ‘OU=SomeUserOU,DC=Company,DC=com’ -Filter * | foreach {write-output $.name}
But not this
get-aduser -SearchBase ‘OU=SomeUserOU,DC=Company,DC=com’ -Filter * | Write-Output $

Thanks in advance

Because $_ is a special token. It isn’t universally recognized everywhere - it’s only used in places where PowerShell is designed to recognize it, as in ForEach-Object or Where-Object. Well-covered in “Learn Windows PowerShell in a Month of Lunches” if you’re interested.

The automatic $_ variable is only set in certain circumstances, typically when you’re using a script block of some sort (Where-Object / ForEach-Object / Catch blocks / etc). There’s one other syntax you didn’t try which should probably work in this case, though it’s a little bit obscure:

get-aduser -SearchBase 'OU=SomeUserOU,DC=Company,DC=com' -Filter * | Write-Output { $_.Name }

This works because Write-Output’s -InputObject parameter happens to accept pipeline input, and anytime you pass a script block as a parameter to something that accepts pipeline input (assuming that the parameter is not actually of type ScriptBlock), PowerShell will wait until it receives pipeline input to bind that parameter’s value. (And inside the script block, the $_ variable is available). The end result is the same as your ForEach-Object example, but with slightly better performance.

Even better would just be this:

get-aduser -SearchBase 'OU=SomeUserOU,DC=Company,DC=com' -Filter * | Select-Object -ExpandProperty Name

Thank you for your quick reply.
I’ve just started reading the book.