What does $_ mean in PowerShell?

Powershell

Powershell Problem Overview


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

$_

Powershell Solutions


Solution 1 - Powershell

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 - Powershell

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 - Powershell

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 - Powershell

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

Solution 5 - Powershell

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

Solution 6 - Powershell

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

Solution 7 - Powershell

The $_ is a $PSItem, which is essentially an object piped from another command. For example, running Get-Volume on my workstations returns Rows of PSItems, or objects

get-volume | select driveLetter,DriveType   

driveLetter DriveType
----------- ---------
      D      Fixed
             Fixed
      C      Fixed
      A      Removable

Driveletter and DriveType are properties Now, you can use these item properties when piping the output with $_.(propertyName). (Also remember % is alias for Foreach-Object) For example

$vol = get-volume | select driveLetter,DriveType

$vol | Foreach-Object {
    if($_.DriveType -eq "Fixed") {
        "$($_.driveLetter) is $($_.driveType)"}
     else{
        "$($_.driveLetter) is $($_.driveType)"
     }
 }

Using Terinary in Powershell 7, I am able to shorten the logic while using properties from the Piped PSItem

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMicahView Question on Stackoverflow
Solution 1 - PowershellJaredParView Answer on Stackoverflow
Solution 2 - PowershellSergey TeplyakovView Answer on Stackoverflow
Solution 3 - PowershellIkkeView Answer on Stackoverflow
Solution 4 - PowershellJeter-workView Answer on Stackoverflow
Solution 5 - PowershellAlex SarafianView Answer on Stackoverflow
Solution 6 - PowershellBillView Answer on Stackoverflow
Solution 7 - PowershellDaikyuView Answer on Stackoverflow