What does $_ mean in PowerShell?

% is an alias for the ForEach-Object cmdlet.

An alias is just another name by which you can reference a cmdlet or function. For example dir, ls, and gci are all aliases for Get-ChildItem.

ForEach-Object executes a [ScriptBlock] for each item passed to it through the pipeline, so piping the results of one cmdlet into ForEach-Object lets you run some code against each individual item.

In your example, Get-ChildItem is finding all of the bins in a certain directory tree, and then for each one that is found, Get-ChildItem is being used to find all of the files underneath that match *.Unit.Tests.dll, and then for each one of those, the full name is returned to the pipeline (which is getting assigned to the $tests variable).


Adding to @briantist's answer:

The | is the pipeline operator. From the docs:

Each pipeline operator sends the results of the preceding command to the next command.

To demonstrate:

Get-ChildItem bin | % { Get-ChildItem $_  }

could be rewritten as:

Get-ChildItem bin | Foreach-Object { Get-ChildItem $_ }

or without using the pipeline but a foreach loop instead (which is different from the foreach command!):

foreach ($item in (Get-ChildItem bin)) { Get-ChildItem $item }

Tags:

Powershell