Learning about the pipeline

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Hafsteinn Þórðarson Hafsteinn Þórðarson 2 months, 3 weeks ago.

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #45688

    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
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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

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

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.