In this answer the author proposed the following snippet:
dir -Path C:\FolderName -Filter *.fileExtension -Recurse | %{$_.FullName}
I can understand the majority of it, but I'm unable to search documentation for the last part. The output of the search is piped |
and used in %{}
and as $_
.
I have experimented around it, %{}
is a for-each statement I believe, bing search was not effective. $_
is also somewhat magic: it is a variable, with no name and thus immediately consumed? I don't care much for the .FullName
, that part I sorted out. Again, bing search was not effective, nor searching for those char sequences in PowerShell docs.
Can anybody explain it to me?
%{}
is not "a thing" - it's two things:%
and{}
%
is an alias for theForEach-Object
cmdlet:... so it resolves to:
ForEach-Object
is basically PowerShell'smap
function - it takes input via the pipeline and applies the operation described in the{}
block to each one of them.$_
is an automatic reference to the current pipeline input item being processedYou can think of it a bit like a
foreach($thing in $collection){}
loop:Except we can now stick our loop in the middle of a pipeline and have it produce output for immediate consumption:
ForEach-Object
is not the only thing that makes use of the$_
automatic variable in PowerShell - it's also used for pipeline-binding expressions:... as well as property expressions, a type of dynamic property definition supported by a number of cmdlets like
Sort-Object
:...
Group-Object
:... and
Select-Object
: