Guy recommends :
Free SolarWinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



Windows PowerShell $_. Variable

Introduction to the PowerShell Dollar 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 {$_.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 $_.

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

# 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:  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: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.  Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server.

Download your free copy of WMI Monitor

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 1: 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 2:  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.

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 it's followed by the -replace parameter rather than a .property.

The purpose of this script is to remove and duplicate "the the" 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", "the"} | Set-Content $str
}

Guy Recommends:  SolarWinds' Free Bulk Import ToolFree Download of Solarwinds  Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click to import the users.  Optionally, you can provide the name of the OU where the new accounts will be born.

There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:

  1. Bulk-import new users into Active Directory.
  2. Seek and zap unwanted user accounts.
  3. Find inactive computers.

Download your FREE bulk import 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 Name Description
$_ The current pipeline object; used in script blocks, filters, the process clause of functions, where-object, foreach-object and switch
$Args  Used in creating functions that require parameters
$Env:Path Environmental Path to files.
$Error  If an error occurred, the object is saved in the $error PowerShell variable
$foreach Refers to the enumerator in a foreach loop.
$HOME The user's home directory; set to %HOMEDRIVE%\%HOMEPATH%
$Input Input piped to a function or code block
$Match A hash table consisting of items found by the -match operator.
$Host Information about the currently executing host
$LastExitCode The exit code of the last native application to run
$true Boolean TRUE
$false Boolean FALSE
$null A null object
$ShellID The identifier for the shell.  This value is used by the shell to determine the ExecutionPolicy and what profiles are run at startup.
$StackTrace  contains detailed stack trace information about the last error

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 PowerShell examples

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

Syntax   • Variables   • -whatIf   • -ErrorAction   • Windows PowerShell   • PowerShell 2.0

PowerShell Functions   • [System.Math]   • Get-Credential   • Windows 7 PowerShell 2.0

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.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, SolarWinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2012 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: