Learning about the pipeline

Welcome Forums General PowerShell Q&A Learning about the pipeline

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
2 years, 6 months ago.

  • Author
    Posts
  • #45688

    Participant
    Points: 0
    Rank: Member

    Hi everybody

    Here is my novice question 🙂

    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 $_.name

    Thanks in advance

  • #45694

    Keymaster
    Points: 1,785
    Helping HandTeam Member
    Rank: Community Hero

    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.

  • #45696

    Member
    Points: 0
    Rank: Member

    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
    
  • #45698

    Participant
    Points: 0
    Rank: Member

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

The topic ‘Learning about the pipeline’ is closed to new replies.