Windows PowerShell


Windows PowerShell Variables

Introduction to Windows PowerShell Variables

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

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.

Topics for PowerShell's Variables

 ♣

PowerShell's $Dollar variables

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.

$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

[int]$a =7

$a +3
$a
10

$a ="Twenty"
$a
Error "Cannot Convert value.

Note: I cannot resist pointing out the [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
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 gives me no 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.

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: SolarWinds Engineer's Toolset v10Engineer's Toolset v10

The Engineer's Toolset v10 provides a comprehensive console of utilities for troubleshooting computer problems.  Guy says it helps me monitor what's occurring on the network, and the tools teaches me more about how the system literally operates.

There are so many good gadgets, it's like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.  Download your copy of the Engineer's Toolset v 10

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: set-variable Thermometer 32 -option constant. 

Note 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: set-variable AllOverPlace 99 -scope global.

Note: 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:

$global:runners = 8

Note this time you start with a dollar and employ the equals sign.

PowerShell's Dot Properties.

PowerShell variables support the dot (.) properties.  For example:

$alert = Get-service alerter
$alert.status

Result at the PowerShell command line:
Stopped

Not only is $variable.property a neat technique, but 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)

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: 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*".

Solarwinds LANSurveyorGuy Recommends: A Free tool from SolarWinds: Config Generator

Config Generator (CG) is a free tool, which puts you in charge of controlling changes to network routers and other SNMP devices.  Boost your network performance by activating network device features you've already paid for.

Guy says that for newbies the biggest benefit of this free tool is that it will provide the impetus for you to learn more about configuring the SNMP service with its 'Traps' and 'Communities'.  This is a brand new free utility which Solarwinds released on January 26th 2010.

Download your free copy of the Config Generator

More Built-in PowerShell Variables

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

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

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

See more Microsoft PowerShell tutorials:

PowerShell Home  • Com  • Shell Application  • Active Directory  • QAD Snap-in  • Get-Member

Please write in if you see errors of any kind.  Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.

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.

 *


Google

Web  This website

Review of Orion NPMGuy Recommends: Orion's NPM - Network Performance Monitor

Orion's performance monitor is designed for detecting network outages. A network-centric view make it easy to see what's working, and what needs your attention.

This utility guides you through troubleshooting by indicating whether the root cause is faulty equipment or resource overload.

Download a free trial of the Network Performance Monitor

 

Home Copyright © 1999-2010 Computer Performance LTD All rights reserved

Please report a broken link, or an error.