What does $_ mean in PowerShell?

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

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

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

    $_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object.

    But it can be used also in other types of expressions, for example with Select-Object combined with expression properties. Get-ChildItem | Select-Object @{Name="Name";Expression={$_.Name}}. In this case the $_ represents the item being piped but multiple expressions can exist.

    It can also be referenced by custom parameter validation, where a script block is used to validate a value. In this case the $_ represents the parameter value as received from the invocation.

    The closest analogy to c# and java is the lamda expression. If you break down powershell to basics then everything is a script block including a script file a, functions and cmdlets. You can define your own parameters but in some occasions one is created by the system for you that represents the input item to process/evaluate. In those situations the automatic variable is $_.

提交回复
热议问题