PowerShell$_语法
在这个答案中,作者提出了以下片段:
dir -Path C:FolderName -Filter *.fileExtension -Recurse | %{$_.FullName}
我可以理解其中的大部分内容,但我无法搜索最后一部分的文档。搜索的输出通过管道传输|并在%{}和 as 中使用$_。
我已经围绕它进行了实验,%{}我相信是一个 for-each 语句,bing search 是无效的。$_也有点神奇:它是一个变量,没有名字,因此立即被消耗?我不太关心.FullName我整理出来的那部分。同样,bing 搜索无效,也无法在 PowerShell 文档中搜索这些字符序列。
有人可以向我解释一下吗?
回答
%{}不是“一件事” - 这是两件事:%和{}
%是ForEach-Objectcmdlet的别名:
PS ~> Get-Alias '%'
CommandType Name Version Source
----------- ---- ------- ------
Alias % -> ForEach-Object
...所以它解析为:
... |ForEach-Object { $_.FullName }
ForEach-Object基本上是 PowerShell 的map功能- 它通过管道获取输入并将{}块中描述的操作应用于其中的每一个。
$_ 是对当前正在处理的管道输入项的自动引用
你可以把它想象成一个foreach($thing in $collection){}循环:
1..10 |ForEach-Object { $_ * 10 }
# produces the same output as
foreach($n in 1..10){
$n * 10
}
除了我们现在可以将循环放在管道中间并让它产生输出以供立即使用:
1..10 |ForEach-Object { $_ * 10 } |Do-SomethingElse
ForEach-Object并不是唯一$_在 PowerShell 中使用自动变量的东西——它还用于管道绑定表达式:
mkdir NewDirectory |cd -Path { $_.FullName }
...以及属性表达式,一种由许多 cmdlet 支持的动态属性定义类型,例如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
- One nice thing about Visual Studio Code is if you install the powershell addin it will warn you about using alias and tell you what the alias refers to.