PowerShell Basics: $_. Pipeline Variable | Examples

PowerShell Basics_ $_. Pipeline Variable

Introduction to the PowerShell Dollar Underscore Variable

Constructions such as … | Where {$_.name -Match “win”} are incredibly useful in PowerShell.  Definitions such as: ‘$_ means in this pipeline’, are a bit stuffy.  The best way to understand $_ is to work through examples.

Examples of the PowerShell $_ Variable

PowerShell’s $_ Variable

The first point to remember is that $_ is a variable or placeholder.


# PowerShell $_ Variable Example
Get-Service | Where-Object {$_.name -Match "win"}

What we want to say here is
Get the services, where the service name matches ‘Win’.  Did the repetition of ‘service’ seem a little verbose?  Well, script writing is brilliant at eliminating extraneous words?

In a nutshell $_ saves us repeating Get-Service, or whatever else may be to the left of … | Where{$_

The Significance of the Dot in PowerShell’s $_.PowerShell Dollar Variable

Here is a similar dollar underscore example but featuring .DisplayName instead of .Name.  My point is I want to illustrate how the .dot command introduces a property.

If you use PowerShell’s ISE GUI, then as soon as you type that period (.) you get a drop-down list of properties.


# PowerShell $_ Variable Example
Get-Service | Where {$_.DisplayName -Match "win"}

Challenge:  Research more properties with Get-Service | Get-Member.

$_ Example to Filter WmiObjects

The key to remembering the syntax is to breakdown the construction in to:  $dollar / _underscore / dot.property.  The commonest example would be: $_.name.


# PowerShell script to find Network WMI Objects
Get-WmiObject -List | Where-Object {$_.name -Match 'Network'}

Note 1: The real-life task is to research for network type WMI objects.  Without the where clause it would be like looking for a needle in a haystack.

Guy Recommends:  Network Performance Monitor (FREE TRIAL)Review of Orion NPM v11.5

SolarWinds Network Performance Monitor (NPM) will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM on a 30-day free trial.

SolarWinds Network Performance Monitor Download 30-day FREE Trial

 The PowerShell Variable $_

Another way of looking at PowerShell’s $_ is purely as a variable.  After all, the dollar sign is PowerShell’s way of introducing any variable, not just this special ‘In this pipeline’ item.


#PowerShell Script to List Dll files
$Path = "C:\Windows\System32\"
Get-ChildItem $Path | Where {$_.extension -eq '.DLL'}

Note 2: The point of this example is to compare the special $_ variable with an ordinary variable called $Path.

Significance of the Where {Evaluation}

Most of the $_ examples feature the ‘where’ filter.  While many scripters also like the alias ?, the underlying cmdlet is: Where-Object.  Let us take the time to research its properties.


Clear-Host
Get-Help Where-Object -full

Note 3: Remember that Where-Object is a filter; therefore to perform its job Where needs a ScriptBlock to evaluate the test.  Actually, the two characters ‘$ and _’ play a small but important role; $_’s job is to shorten the evaluation by saying, ‘In this pipeline’, rather than explicitly mentioning the test for a second time.

See more on measuring the speed of Where-Object

PowerShell $_ with ForEach

Most of my $_ examples are found in Where-Object clauses, but here is a different use for this special pipeline variable: ForEach.  Once again, observe that $_ is the first item inside the curly brackets, but this time the underscore is followed by the -replace parameter rather than a .property.

The purpose of this script is to remove and duplicate “the the” in documents stored in the ProofRead folder.

Clear-Host
$file = gci “D:\ProofRead\*.doc”
$file
ForEach ($str in $file)
{
$cont = Get-Content -path $str
$cont
$cont | ForEach {$_ -replace “the , “the”} | Set-Content $str
}

Note 4: In the ForEach example the syntax is purely $_ there is no (.) property.

Guy Recommends: Free WMI Monitor for PowerShell (FREE TOOL)Solarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor for PowerShell so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guesswork out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

SolarWinds WMI Monitor Download 100% Free Tool

More of PowerShell’s Built-In Variables

You can enumerate PowerShell’s variables with this command:


Get-Variable | Format-Table name, value -auto
Variable NameDescription
$_The current pipeline object; used in script blocks, filters, the process clause of functions, where-object, ForEach-object and switch
$ArgsUsed in creating functions that require parameters
$Env:PathEnvironmental Path to files.
$ErrorIf an error occurred, the object is saved in the $error PowerShell variable
$ForEachRefers to the enumerator in a ForEach loop.
$HOMEThe user’s home directory; set to %HOMEDRIVE%\%HOMEPATH%
$InputInput piped to a function or code block
$MatchA hash table consisting of items found by the -Match operator.
$HostInformation about the currently executing host
$LastExitCodeThe exit code of the last native application to run
$trueBoolean TRUE
$falseBoolean FALSE
$nullA null object
$ShellIDThe identifier for the shell.  This value is used by the shell to determine the ExecutionPolicy and what profiles are run at startup.
$StackTracecontains detailed stack trace information about the last error

See also PowerShell’s Get-PSProvider »

Summary of PowerShell $_ Variable

Perhaps the key to understanding this construction is to look at what follows $_.  For example, $_.Name leads us to think, ‘Name is a property in the current ScriptBlock, or PowerShell pipeline.  Further reflection shows that $_ saves scripting space by substituting two characters for a whole extra construction.

If you like this page then please share it with your friends


See more Windows PowerShell  examples of variables

Syntax   • PowerShell Variables   • Get-PSProvider   • PowerShell Dollar Variable

PowerShell Functions   • Get-PSDrive   • PowerShell New-PSDrive   • Remove-PSDrive

PowerShell Home   • Foreach loops   • PowerShell Foreach   • Foreach-Object cmdlet

Please email me if you have a better example script.  Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.