Understanding and Creating Windows PowerShell 1.0 Variables

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Directing and Formatting Windows PowerShell 1.0 OutputBasic Windows PowerShell 1.0 Types

Purchase and download the full PDF version of this PowerShell eBook for only $8.99

Buy eBook

A large part of writing scripts, and for that matter programming in general, involves the handling and manipulation of data. Data can take many forms, ranging from single characters, words and sentences to integers, floating point numbers and true and false values. In object-based scripting environments such as Windows PowerShell, data can also take the form of an object, a self contained module which is capable of encapsulating any number of data values of numerous different types.

When working with data values in PowerShell, we need some convenient way to store these values so that we can easily access them and make reference to them whenever necessary. This is where PowerShell variables come in.

It is often useful to think of variables as computer memory locations where data is to be stored. When declaring a variable in PowerShell, it is assigned a name that can used to reference it in other locations in the PowerShell script. The value of the variable can be accessed, the value can be changed, and the type of variable can be altered all by referencing the name assigned at variable creation time.

Naming a Variable in PowerShell

In PowerShell, all variable names must begin the dollar sign ($). In general any string comprising numbers and letters and pre-fixed with a $ can be used as a variable name, with the exception of pre-defined variable names and $_.

Let's look at some valid and invalid PHP variable names:

$myName # valid
$_myvar # valid
$myVar21 # valid
$1greatvariable #valid
$mystring-1 # invalid - contains a non-alphanumeric character (-)
$mystring+1 # invalid - contains a non-alphanumeric character (+)

Variable names in PowerShell are case-insensitive. This means that PowerShell considers $myvariable to be the same variable name as ''$MyVariable.

Creating and Assigning a Value to a PowerShell Variable

Values are assigned to variables using the PowerShell assignment operator, represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is then placed to the right of the assignment operator.

PowerShell is a loosely typed language. In contrast to strongly typed languages such as C#, C++ or Java this means that the type of the variable does not need to be specified at creation time. Instead, PowerShell infers the type from the data being assigned. For example, let's begin by assigning the word "Red" to a variable named mycolor:

$mycolor = "Red";

We have now declared a variable with the name mycolor and assigned a string value to it of "Red". Since "Red" is clearly a string, PowerShell safely assumes the variable is of type string.

We can similarly declare a variable to contain an integer value:

$numberofcolors =  6;

The above assignment creates a variable named numberofcolors and assigns it a numeric value of 6. Once again, the type of the variable can be inferred by PowerShell, in this case an Int32 number. In fact, since all types are essentially objects, the type of a variable may be identified at any time by calling the GetType() method of the object:

PS C:\Users\Administrator> $numberofcolors.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

Having said that PowerShell is a loosely typed language, it is important to note that the data type may be explicitly declared if desired. For example:

$numberofcolors = [int32] 6

Once a variable has been created, the value assigned to that variable can be changed at any time using the same assignment operator approach:

$numberOfShapes =  6 # Set initial values
$myShape = "Circle"; 

$numberOfShapes =  7; # Change the initial values to new values
$myShape = "Square"

Accessing PowerShell Variable Values

Now that we have learned how to create a variable and assign an initial value to it we now need to look at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple as referencing the name it was given when it was created.

For example, if we want to display the value which we assigned to our numberofcolors variable we can simply reference it in a command:

"The number of colors is $numberofcolors."

This will cause the following output to appear in the browser:

The number of colors is 6.

Similarly we can display the value of the mycolor variable:

"$mycolor is the current color.";

Changing the Type of a PowerShell Variable

As we mentioned at the beginning of this chapter, PowerShell supports a number of different variable types. We will look at these types in detail in the next chapter (Windows PowerShell 1.0 Types). First we are going to look at changing the type of a variable after it has been created.

As previosuly mentioned, PowerShell is what is termed a loosely typed language. This contrasts with programming languages such as Java which are strongly typed languages. The rules of a strongly typed language dictate that once a variable has been declared as a particular type, its type cannot later be changed. In Java, for example, you cannot assign a floating point number to a variable that was initially declared as being a string.

Loosely typed languages such as PowerShell (and JavaScript), on the other hand, allow the variable type to be changed at any point in the life of the variable simply by assigning a value of a different type to it. For example, we can create a variable, assign it an integer value and later change it to a string type by assigning a string to it:

$myNumber = 6 # variable is of int32 type

$myNumber = "six" # variable has now changed to string type

The process of dynamically changing the type of a variable is sometimes referred to as automatic type conversion.

Pre-defined PowerShell Variables

In an early section of this chapter the existence of pre-defined Windows PowerShell variables was mentioned (specifically, it is not possible to create a variable using a name assigned to a pre-defined variable). The final area to be covered in this chapter, therefore, is to list some of the more useful pre-defined variables:

Variable Name



Boolean true value


Boolean false value


Object collection separator


The current user's home directory


The directory into which PowerShell is installed.


The parameters passed through to a PowerShell function


The current content of the pipeline.


Contains current stack trace information.


Information about the host in which PowerShell is running.


The exit code returned by the last executed native Windows executable.


List of all errors since invocation of PowerShell session (up to maximum defined by $MaximumErrorCount).


The maximum number of errors to be recorded during a single PowerShell session. Default is 256.


The current pipeline object; used in script blocks, filters, functions and loops.


The first token of the preceding command line


The last token of the preceding command line


The current value of the enumerator of a foreach loop.


The completion status (true or false) of the preceding command.


The NULL object.


Information about the current script line or command. Includes script line number, offset into line, script name, and pipeline position details.


Hash table of matches generated by the -match parameter


The identifier of the currently running shell.