我在PowerShell中见过很多下面的代码,但是它到底是做什么的呢?
$_
发布于 2010-08-16 22:36:09
这是管道中的当前值的变量,在Powershell3和更高版本中称为$PSItem
。
1,2,3 | %{ write-host $_ }
或
1,2,3 | %{ write-host $PSItem }
例如,在上面的代码中,数组中的每个值都会调用%{}
块。$_
或$PSItem
变量将包含当前值。
发布于 2010-08-21 05:57:24
我认为理解这个变量的最简单的方法就是在C#的lambda表达式中输入参数。也就是说,$_
类似于C#中x => Console.WriteLine(x)
匿名函数中的x
。考虑以下示例:
PowerShell:
1,2,3 | ForEach-Object {Write-Host $_}
打印:
1
2
3
或
1,2,3 | Where-Object {$_ -gt 1}
打印:
2
3
并将其与使用LINQ的C#语法进行比较:
var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));
打印:
1
2
3
或
list.Where( _ => _ > 1)
.ToList()
.ForEach(s => Console.WriteLine(s));
打印:
2
3
发布于 2015-11-07 00:36:25
$_是自动变量$PSItem (在PowerShell V3.0;Usage information found here中引入)的别名,表示管道中的当前项。
有关自动变量的PowerShell (v6.0)在线文档是here。
https://stackoverflow.com/questions/3494115
复制相似问题