PowerShell, a versatile scripting language for Windows environments, introduces the $_ (underscore) variable, a fundamental component in the pipeline operation. This variable is used to reference the current object being processed, particularly within cmdlets that operate on objects in a pipeline. See the following sample usages:

ForEach-Object: Iterating through Objects

The ForEach-Object cmdlet allows the iteration through a collection of objects. The $_ variable is employed to reference the current object within the script block.

$numbers = 1, 2, 3, 4, 5

$numbers | ForEach-Object {
    "Current value is: $_"
}

In this example, $_ represents each number in the array during the iteration.

Where-Object: Filtering Objects

With Where-Object, you can filter objects based on specified criteria. The $_ variable is used to reference the current object within the script block defining the filtering condition.

$numbers = 1, 2, 3, 4, 5
$numbers | Where-Object { $_ -gt 2 }

Here, $_ is employed to compare each number in the array and filter those greater than 2.

Select-Object: Customizing Object Output

Select-Object is utilized for customizing the output of selected properties. The $_ variable is used to reference the current object's properties.

Get-Process | Select-Object Name, @{Name='Memory (MB)'; Expression={$_.WorkingSet / 1MB}}

In this example, $_ enables the selection and manipulation of properties for each process in the pipeline.

Sort-Object: Sorting Objects

Sorting objects with Sort-Object involves specifying a script block. The $_ variable is used to reference the current object for sorting.

Get-Service | Sort-Object {$_.Status}

Here, $_ is utilized to determine the sorting order based on the Status property of each service.

Group-Object: Grouping Objects

Group-Object groups objects based on a specified property. The $_ variable is essential for referencing the current object during the grouping process.

Get-Process | Group-Object {$_.PriorityClass}

In this instance, $_ plays a key role in grouping processes based on their PriorityClass property.

Understanding and effectively utilizing the $_ variable empowers PowerShell users to manipulate objects within the pipeline, providing flexibility and control over script operations.