What does $_ mean in PowerShell?

后端 未结 6 938
孤城傲影
孤城傲影 2020-12-02 04:07

I\'ve seen the following a lot in PowerShell, but what does it do exactly?

$_
6条回答
  •  没有蜡笔的小新
    2020-12-02 05:05

    I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_ is similar to x in x => Console.WriteLine(x) anonymous function in C#. Consider following examples:

    PowerShell:

    1,2,3 | ForEach-Object {Write-Host $_}
    

    Prints:

    1
    2
    3
    

    or

    1,2,3 | Where-Object {$_ -gt 1}
    

    Prints:

    2
    3
    

    And compare this with C# syntax using LINQ:

    var list = new List { 1, 2, 3 };
    list.ForEach( _ => Console.WriteLine( _ ));
    

    Prints:

    1
    2
    3
    

    or

    list.Where( _ => _ > 1)
        .ToList()
        .ForEach(s => Console.WriteLine(s));
    

    Prints:

    2
    3
    

提交回复
热议问题