Reputation: 531
I've come across this today:
$tests = (Get-ChildItem . -Recurse -Name bin |% { Get-ChildItem $_ -Recurse -Filter *.Unit.Tests.dll } |% { $($_.FullName) })
Write-Host ------------- TESTS -----------
Write-Host $tests
Write-Host -------------------------------
.\tools\xunit\xunit.console.exe $tests -xml test-report.unit.xml
I can't get my head around what '|%' is doing there. Can anyone explain what it used for please?
Upvotes: 14
Views: 20793
Reputation: 17055
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 }
Upvotes: 4
Reputation: 47792
%
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 bin
s 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).
Upvotes: 12