What does $_ mean in PowerShell?
I've seen the following a lot in PowerShell, but what does it do exactly?
$_
Solution 1:
This is the variable for the current value in the pipe line, which is called $PSItem
in Powershell 3 and newer.
1,2,3 | %{ write-host $_ }
or
1,2,3 | %{ write-host $PSItem }
For example in the above code the %{}
block is called for every value in the array. The $_
or $PSItem
variable will contain the current value.
Solution 2:
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<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));
Prints:
1
2
3
or
list.Where( _ => _ > 1)
.ToList()
.ForEach(s => Console.WriteLine(s));
Prints:
2
3
Solution 3:
According to this website, it's a reference to this
, mostly in loops.
$_ (dollar underscore) 'THIS' token. Typically refers to the item inside a foreach loop. Task: Print all items in a collection. Solution. ... | foreach { Write-Host $_ }
Solution 4:
$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.
PowerShell (v6.0) online documentation for automatic variables is here.