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 Variables

Introduction to Windows PowerShell Variables

All scripting languages use placeholders or variables to hold data.  Furthermore, each language has its own rules and symbols.  I have found that using any PowerShell variable is straightforward, just remember to  introduce your PowerShell variable with a dollar sign, for example: $memory.

Topics for PowerShell's Variables

 ♣

PowerShell's $Dollar Variables

Variables are handy for storing data which can be used later in the script. For example, storing a file path. Creating a PowerShell variable could not be more straightforward; just put the dollar sign in front of the name you wish to call the variable.  Let us create, then set, a variable called $Mem:

$Mem= WmiObject Win32_ComputerSystem

Once we have created $Mem, then we can put the variable to work and calculate the RAM memory in Mega bytes.

# PowerShell $ Variable Example
$Mem= WmiObject Win32_ComputerSystem
$Mbyte =1048576 # Another variable
"Memory Mbyte " + [int]($Mem.TotalPhysicalMemory/$Mbyte)

PowerShell has no built-in mechanism for enforcing variable types, for example, string variables can begin with letters or numbers. Yet numeric variables can also begin with letters (or numbers). However, you can restrict the values a PowerShell variable accepts by preceding it with [int] or [string], for example:

Example Declaring the PowerShell Variable as an Integer

# Declaring PowerShell Integer Variable
[int]$a =7
$a +3
$a
# PS>10

 

# Declaring PowerShell Integer Variable
[int]$a =7
$a ="Twenty"
$a

# PS> Error "Cannot Convert value.

Note 1: I cannot resist pointing out the significance of [Square brackets].  The reason is that PowerShell only ever uses square brackets for optional items, and declaring the type of a variable is just that - optional.

Example Without Declaring the Variable Type.

$b = 7
$b = "Twenty"
$b

# PS> Twenty 

No error here because $b was not declared as number or a string.

Do you think that PowerShell variables are case sensitive or insensitive?  The answer is insensitive, just as with most other commands, upper or lower case work equally.

When PowerShell evaluates a potential variable name, it carries on from the $Dollar until it meets a word breaking character such as a space or punctuation mark.  This does not give me a problem because I only use snappy OneWord names, but if you use variables with strange characters - watch out!  If you insist on using variables with names such as a*?,v**, then you could enclose them in braces - thus {a*?,v**}.  Clever stuff, but best to keep it simple and don't ask for trouble I say.

Reserved Words - Not To Be Used For Variables

Avoid using these reserved keywords for your variables: Break, continue, do, else, elseif, for, foreach, function, filter, in, if, return, switch, until, where and while.

Incidentally, you can join string variables simply by using a plus (+) sign. The reason that I mention this is because I spent ages searching fruitlessly for a special text concatenator, only to discover that the plain plus sign was all I needed.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v10

SolarWinds' Orion performance monitor 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.

Perhaps the NPM's best feature is the way it suggests solutions to network problems.  Its second best feature is 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 take advantage of SolarWinds' offer.

Download a free trial of the Network Performance Monitor.

Declaring Multiple Variables

In scripting we are always seeking ways of writing tighter code.  In the case of variables you can make multiple declarations on the same line. For example:

$DriveA, $DriveB, $DriveC, $DriveD = 250, 175, 330, 200

PowerShell Variables - Text Examples

What you find when researching WMI objects is that there are so many.  The purpose of this script is filter, or home in on, a keyword such as Win32, or network.  To aid the research and to recycle the code I introduce a variable $Type.

To begin with I set the value of $Type to "Win32", later it would be a trivial task to amend to "Network".  Once again, note how this script uses the built in $_. variable, and see how it uses .name in this pipeline.

# PowerShell Variables Including $_.
$i=0
$Type = "Win32"
$WMI = Get-wmiobject -list | Where-Object {$_.name -match $Type}
Foreach ($CIM in $WMI) {$i++}
Write-Host 'There are '$i' types of '$Type

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

Set-Variable, Scope and Option

You can control, or restrict, PowerShell variables with the set-Variable command.  These extra properties of 'Option' and 'Scope' are not really necessary for beginners, nevertheless as you grow in ambition, you may like to revisit these additional features.

Option can set the variable to be read-only or constant.  Constant variables sound strange, but their killer feature is they cannot be deleted.

# Example: PowerShell Set-Variable constant
Set-Variable Thermometer 32 -option constant. 

Note 2: That when initializing with set-variable, $Thermometer is wrong, plain Thermometer is what you need here.  Once the value is set to 32 it cannot be changed.

Scope can be local, global or script.  The default value for the scope of a variable is local. 

# Example: PowerShell Set-Variable Global
Set-Variable AllOverPlace 99 -scope global

Note 3: For more information about Set-Variable, try Help Set-Variable.

Note 4: The value would be 99, again you don't add the $dollar sign when you execute set-variable.  Actually, there is an alternative method for setting and creating Scope:

# Set PowerShell Global Variable
$global:runners = 8

PowerShell's Dot Properties

Before we look at the pipeline variable $_.  let us have a general look at PowerShell .dot properties. PowerShell variables support the dot (.) properties.  For example:

$alert = Get-Service NetLogon
$alert.status

# PS> Started

Not only is $variable.property a neat technique, but also note that Get-Service alerter.status does not work, you get an error saying: 'Cannot find any service called alerter.status'.

Special Pipeline Variable:  $_.

$_ or $_. takes the dot notation one stage further.  It acts a placeholder for the current object.  The official definition for $_. is the current pipeline object; used in script blocks, filters, the process clause of functions, where-object, foreach-object and switches.  However, I believe that special PowerShell variable $_. is best explained by examples.

PowerShell Example to find all services that are Running (not stopped)

# PowerShell Pipeline $_. example
Get-Service | where {$_.status -eq "Running" }

Remember that this Get-Service command lists all those services on the machine.  Status is a property of the service.  One of the possible values for status is "Running", another value is "Stopped".  Should you wish to employ a 'where' clause, then you need the $_. variable to introduce or link to the property 'status', hence $_.status.

Example to find all wmiobject containing 'CIM'

Get-WmiObject -list | where-object {$_.name -like "CIM*"}

Note 5: The point is that the list is too long when you try:
Get-wmiobject -list

By pipelining $_.name, we can filter just names containing "CIM".  Incidentally it does not work without the wildcard * -like "CIM*".  However you could experiment with -match, or -contains.

See more on PowerShell's $_.  meaning In the Current Pipeline

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 Built-in PowerShell Variables

You can enumerate PowerShell's variables with this command:

Get-Variable

Another example showing more information and more control:

Get-Variable | ft 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
$^  contains the first token of the last line input into the shell
$$  contains the last token of last line input into the shell
$?  Contains the success/fail status of the last statement
$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.
$MyInvocation Information about the currently script or command-line
$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
$OFS Output Field Separator, used when converting an array to a string.
By default, this is set to the space character.
$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

PowerShell Variables in Action

Example 1)
To discover which version of PowerShell you are running, go to the PowerShell command line and type:
$host

Example 2)
You could modify the Environment Path value thus:

®

$Env:Path = $Env:Path + ";C:\Wizzo\Stuff"

Note 6: The plus (+) means that you keep the existing path locations and append C:\Wizzo\Stuff

Note 7: Talking of Env variables, you can list them with gci thus:

Get-ChildItem Env:\

PowerShell Variable Theory

PowerShell variables are mapped to classes in the Microsoft .NET Framework. One benefit is that variables are objects and thus can be manipulated in many ways.  There is also a family of variable cmdlets which you can see with this command:

Get-Command -noun variable 

Although there is cmdlet called New-Variable, I have never seen anyone use it for real because you can just wade in with a declaration.

$Files = "C:\Windows"  # Is so much easier than New-Variable
Get-ChildItem $Files

Declaring Variables with New-Variable

Remove-Variable $Files
New-Variable files -value "C:\windows"
Get-ChildItem $Files

String and Int32 Variables

PowerShell takes care of strings and numbers automatically, thus you can produce numerous excellent scripts without worrying about this PowerShell theory.

$Files = "C:\Windows" | Get-Member

Result (At the very top of the list)
TypeName System.String

PowerShell takes care of numbers automatically, but assigns the variable to a different class.

$Bit = 64 | Get-Member

Result (At the very top of the list)
TypeName System.Int32

Summary of PowerShell Variables

In PowerShell, variables are easy to create, just precede the name with a dollar sign, for example $Disk.  For more ambitious scripting you can restrict their type for example [int]$Memory, you can also prescribe the variable's scope, local or global.

One variable worth mastering is the special pipeline variable controlled by $_.

What impresses programmers is the ability to assign not just text to the variable, but also to assign an object to a variable.  While most proper scripting languages are able to handle objects through variables, CMD lacks this ability.

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: