tags:

views:

120

answers:

6

I've seen this alot in powershell but not sure what exactly it does:

$_
+3  A: 

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 $_ }

Ikke
+1 for the great link
Micah
+4  A: 

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.

JaredPar
It's not necessarily related to the pipeline. It's more a "current argument to the currently executing script block". For example while you can use it just fine in `ForEach-Object` or `Where-Object` you can't use it in something like `Get-Foo|Add-Member NoteProperty Bar ($_.SomeProperty)` – there's a pipeline involved, but no script block and therefore no `$_`. (That being said, the PowerShell help also refers to the pipeline for `$_`. Confusing.)
Joey
A: 

It's the reference to the piped-in value.

It's similar to this in C# or Me in VB

Benjamin Anderson
Not at all. `this` is a reference to the object instance from within it. That's very unlike `$_`. Unless you write loops in C# in the form of `foreach (bar) { Frob(this); }` – I guess it doesn't quite work that way ;-)
Joey
+2  A: 

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
Sergey Teplyakov
+1  A: 

$_ is an variable which iterates over each object/element passed from the previous | (pipe).

shivashis