I've seen this alot in powershell but not sure what exactly it does:
$_
I've seen this alot in powershell but not sure what exactly it does:
$_
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 $_ }
This is the variable for the current value in the pipe line.
1,2,3 | %{ write-host $_ }
For example in the above code the %{}
block is called for every value in the array. The $_
variable will contain the current value.
It's the reference to the piped-in value.
It's similar to this
in C# or Me in VB
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 => Concole.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
$_ is an variable which iterates over each object/element passed from the previous | (pipe).