What does $_ bind to at the top level of pipelines, in Powershell?

56 views Asked by At

In Powershell, a pipeline can contain filters such as ForEach-Object:

get-process | %{$_.name}

Within the script block of the foreach filter, it's possible to use the $_ auto variable to refer to the current object of the script block.

What does the $_ variable bind to when used at the top level of the pipeline? For example, the following doesn't work:

"common" | get-verb -group $_

I would have thought that it was bound to the resulting object from the previous section of the pipeline -- in the above case, to the "common" string.

I've been looking online for info about how this $_ is bound, but haven't found that type of info. Virtually all examples that I see use $_ within script blocks.

For example, this doesn't answer this question: What does $_ mean in PowerShell?

1

There are 1 answers

1
js2010 On

$_ is only valid inside scriptblocks. Note that -group is a powershell 7 only parameter. You can do something like this, but you have to specify something for the verb:

'comm' | get-verb -group { $_ + 'on' } -verb *


Verb     AliasPrefix Group  Description
----     ----------- -----  -----------
Add      a           Common Adds a resource to a container, or attaches an item to another item
Clear    cl          Common Removes all the resources from a container but does not delete the container
Close    cs          Common Changes the state of a resource to make it inaccessible, unavailable, or unusable
...