PowerShell $_ 语法 [英] PowerShell $_ syntax
问题描述
在这个答案中,作者提出了以下片段:
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 $_
.
我已经围绕它进行了实验,%{}
是我相信的 for-each 语句,无效.$_
也有点神奇:它是一个变量,没有名字,因此立即被消耗?我不太关心 .FullName
,我整理的那部分.同样,bing 搜索无效,也没有在 PowerShell 文档中搜索这些字符序列.
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.
谁能给我解释一下?
推荐答案
%{}
is not "a thing";- 这是两件事:%
和 {}
%{}
is not "a thing" - it's two things: %
and {}
%
is an alias for the ForEach-Object
cmdlet:
PS ~> Get-Alias '%'
CommandType Name Version Source
----------- ---- ------- ------
Alias % -> ForEach-Object
...所以它解析为:
... |ForEach-Object { $_.FullName }
ForEach-Object
基本上是 PowerShell 的 map
函数 - 它通过管道获取输入,并将 {}
块中描述的操作应用于每个输入.
ForEach-Object
is basically PowerShell's map
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 processed
你可以把它想象成一个 foreach($thing in $collection){}
循环:
You can think of it a bit like a foreach($thing in $collection){}
loop:
1..10 |ForEach-Object { $_ * 10 }
# produces the same output as
foreach($n in 1..10){
$n * 10
}
除了我们现在可以将循环放在管道中间并让它产生立即消耗的输出:
Except we can now stick our loop in the middle of a pipeline and have it produce output for immediate consumption:
1..10 |ForEach-Object { $_ * 10 } |Do-SomethingElse
ForEach-Object
不是唯一在 PowerShell 中使用 $_
自动变量的东西——它还用于管道绑定表达式:
ForEach-Object
is not the only thing that makes use of the $_
automatic variable in PowerShell - it's also used for pipeline-binding expressions:
mkdir NewDirectory |cd -Path { $_.FullName }
...以及属性表达式,一种动态属性定义类型,由许多 cmdlet 支持,例如 Sort-Object
:
... as well as property expressions, a type of dynamic property definition supported by a number of cmdlets like Sort-Object
:
1..10 |Sort-Object { -$_ } # sort in descending order without specifying -Descending
... Group-Object
:
1..10 |Group-Object { $_ % 3 } # group terms by modulo congruence
... 和 Select-Object
:
1..10 |Select-Object @{Name='TimesTen';Expression={$_ * 10}} # Create synthetic properties based on dynamic value calculation over input
这篇关于PowerShell $_ 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!