Publish Date: September 22, 2015

Variables in Windows PowerShell

Most programming languages allow the use of variables, which are simply containers which hold the values.

What is Variable

Variable is a container (memory unit) which stores the value. You can store all types of values in Windows PowerShell variables. Variable is typically used to store the result of command and to store elements that are used in commands and expressions, such as names, paths, settings, and values.

In Windows PowerShell, variables are represented by text strings beginning with a dollar sign ($), such as $a, $svc, or $my_var. Variable names are not case-sensitive. Variable names can include spaces and special characters, but these are difficult to use and should be avoided.

Types of Variables

There are three types of variables in Windows PowerShell.

  1. Automatic Variables: Automatic variables store the state of Windows PowerShell. These variables are created by Windows PowerShell, and Windows PowerShell can change their values as required to maintain their accuracy. Users cannot change the value of these variables. For example, the $PSHome variable stores the path to the Windows PowerShell installation directory.
  2. Preference Variables: Preference variables store user preferences for Windows PowerShell. These variables are created by Windows PowerShell and are populated with default values. Users can change the values of these variables. For example, the $MaximumHistoryCount variable determines the maximum number of entries in the session history.
  3. User-defined Variables: User-defined variables are created and maintained by the user. By default, the variables that you create at the Windows PowerShell command line exist only while the Windows PowerShell window is open, and they are lost when you close the window. To save a variable, add it to your Windows PowerShell profile. You can also create variables in scripts with global, script, or local scope.

Working with Variables

To create a new variable, use a text string starting with $ and then use an assignment operator to assign a value to the variable. You do not have to declare the variable before using it. The default value of all variables is $null.

For example, the following commands create two variables $FirstName and $LastName.

PS D:\MyScripts> $FirstName = “Surender”
PS D:\MyScripts> $LastName = “Kumar"

Remember that the $ sign is just a representation of variable. The $ sign is not a part of variable name which means that in the above example the variable names are actually “FirstName” and “LastName”. Windows PowerShell provides a variable: drive which contains all the variables available for your session. I’ve just created two variables above. We should be able to find both of these variables into variable: drive. Let’s take a look at the contents of drive:

PS D:\MyScripts> Get-ChildItem Variable:

Name                           Value
----                           -----
$                              “Kumar"
?                              True
^                              $LastName
args                           {}
ConfirmPreference              High
ConsoleFileName
DebugPreference                SilentlyContinue
Error                          {}
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FirstName                      Surender
FormatEnumerationLimit         4
HOME                           C:\Users\Surender
Host                           System.Management.Automation.Internal.Host.InternalHost
input                          System.Collections.ArrayList+ArrayListEnumeratorSimple
LastName                       Kumar
MaximumAliasCount              4096
MaximumDriveCount              4096

[output cut]

Alternatively, you can use Get-Variable cmdlet to get a list of all of the variables in your Windows PowerShell session.

Variables can also be used for storing the result of commands. For example, the following command will store the result of Get-Service cmdlet into $svc variable.

PS D:\MyScripts> $svc = Get-Service

To display the value of a variable, type the variable name, preceded by a dollar sign ($).

PS D:\MyScripts> $svc

Status   Name               DisplayName
------   ----               -----------
Running  AdobeARMservice    Adobe Acrobat Update Service
Stopped  AeLookupSvc        Application Experience
Stopped  ALG                Application Layer Gateway Service
Running  AmmyyAdmin         Ammyy Admin
Stopped  AmmyyAdmin_690     AmmyyAdmin_690
Stopped  AppIDSvc           Application Identity
Running  Appinfo            Application Information
Stopped  AppMgmt            Application Management
Stopped  AppReadiness       App Readiness

[output cut]

Notice that the value of $svc variable is similar to Get-Service cmdlet. This is because result of Get-Service cmdlet is stored into $svc variable.

To change the value of a variable, assign a new value to the variable. The old value is automatically over-written.

The following examples displays the value of the $FirstName variable, changes the value of the variable, and then displays the new value.

PS D:\MyScripts> $FirstName
Surender
PS D:\MyScripts> $FirstName = "John"
PS D:\MyScripts> $FirstName
John

To delete the value of a variable, use the Clear-Variable cmdlet or change the value to $null.

The following commands delete the values stored in FirstName and LastName variables while the original variables are not deleted.

PS D:\MyScripts> Clear-Variable -Name FirstName
PS D:\MyScripts> $LastName = $null

To delete the variable including their values, use the Remove-Variable or Remove-Item cmdlets as shown below.

PS D:\MyScripts> Remove-Variable -Name FirstName
PS D:\MyScripts> Remove-Item -Path Variable:LastName

Data Type of Variables

You can store any type of object in a variable, including integers, strings, arrays, hash tables, and objects that represent processes, services, event logs, and computers.

Windows PowerShell variables are “loosely typed,” which means that they are not limited to a particular type of object. A single variable can even contain a collection (an “array”) of different types of objects at the same time.

The data type of a variable, which is a .NET Framework type, is determined by the .NET types of the values of the variable. Windows PowerShell automatically determines the data type when you create a variable and assign the value to it.

For example:

PS D:\MyScripts> $a = 10  (System.Int32)
PS D:\MyScripts> $b = "name"  (System.String)
PS D:\MyScripts> $c = 10, "name"  (System.Int32, System.String)
PS D:\MyScripts> $d = Get-ChildItem .  (System.IO.FileInfo)

To determine the data type of a variable, use the GetType method as shown below:

PS D:\MyScripts> $a.GetType()

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

You can use a type attribute and cast notation to ensure that a variable can contain only objects of the specified type or objects that can be converted to that type. If you try to assign a value of another type, Windows PowerShell tries to convert the value to its type. If it cannot, the assignment statement fails.

To use cast notation, enter a type name, enclosed in brackets, before the variable name (on the left side of the assignment statement). The following example creates an $a variable that can contain integers only, a $name variable that can contain string only, and a $today variable that can contain DateTime objects only.

PS D:\MyScripts> [int]$a = 10
PS D:\MyScripts> [string]$name = "John"
PS D:\MyScripts> [datetime]$today = (Get-Date).date

Since our $a variable is set to store only integer data type. Let’s say that you try to store string data type into it, see what happens:

PS D:\MyScripts> $a = "Welcome"
Cannot convert value "Welcome" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ $a = "Welcome"
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

PowerShell tried to convert  value “Welcome” to System.Int32 but it could not convert. So, it could not assign the requested value to variable.

In the following example, Integer 10 is automatically converted into string and stored into variable.

PS D:\MyScripts> $name = 10  (The integer converted into a string)

Use Variables in Scripts and Commands

To use a variable in a script or command, type the variable name, preceded by the dollar sign ($).

If the variable name including dollar sign is not enclosed in quotation marks, or if it is enclosed in double quotation marks (“), the value of the variable is used in the script or command.

If the variable name including dollar sign  is enclosed in single quotation marks (‘), the variable name is used instead of variable value.

In simple words you can say that double quotation marks (“) always expand the variable and use the value stored inside variable, whereas single quotation marks (‘) never expand the variable.

For example, the following commands returns the value of $pshome variable, which is the path to the Windows PowerShell installation. There is no difference between two commands, both work same way since the result is same.

PS D:\MyScripts> $PSHOME
C:\Windows\System32\WindowsPowerShell\v1.0
PS D:\MyScripts> "$PSHOME"
C:\Windows\System32\WindowsPowerShell\v1.0

But the following command does not return the value of $pshome variable, it returns the name of variable as it was written in command.

PS D:\MyScripts> '$pshome'
$pshome

Basically single quotation marks (‘) cause no effect on variable. For better understanding, consider the following line written in a PowerShell script.

PS D:\MyScripts> Write-Host The path of '$pshome' variable is "$pshome"
The path of $pshome variable is C:\Windows\System32\WindowsPowerShell\v1.0

If you want to display the “The path of $pshome variable is C:\Windows\System32\WindowsPowerShell\v1.0” message on console while the script is running, you have to enclose $pshome variable in ‘single quotes’ and “double quotes” exactly as shown in above example.

So, always remember this thing in mind while writing scripts that if you want to use the value of a variable inside your script, enclose the variable name into double quotation marks (“) or just leave the name without any quotation mark. But if you want to use the name of variable, enclose the variable name into single quotation marks (‘).

Create Variables with Special Characters

Variable names begin with a dollar sign ($). They can include alphanumeric characters and special characters. The length of the variable name is limited only by available memory.

Whenever possible, variable names should include only alphanumeric characters and the underscore character (_). Variable names that include spaces and other special characters, are difficult to use and should therefore be avoided.

However in case of special requirement, you can create or display a variable name that includes spaces or special characters, by enclosing the variable name in curly braces. This directs Windows PowerShell to interpret the characters in the variable name literally.

For example, the following command creates and then displays a variable named “My Var”.

PS D:\MyScripts> ${My Var} = "apple", "orange", "mango"
PS D:\MyScripts>
PS D:\MyScripts> ${My Var}
apple
orange
mango

When the variable name also includes braces as a part of name, to refer to a variable name, enclose the variable name in braces, and use the backtick (`) character to escape the braces.

For example, to create a variable named “My {Var} is“, and then display the variable, type the following command:

PS D:\MyScripts> ${My `{Var`} is} = "Hello World!"
PS D:\MyScripts> ${My `{Var`} is}
Hello World!

Scope of Variables

Windows PowerShell protects access to variables, aliases, functions, and Windows PowerShell drives (PSDrives) by limiting where they can be read and changed. By enforcing a few simple rules for scope, Windows PowerShell helps to ensure that you do not inadvertently change an item that should not be changed.

The following are basic rules of scope:

  • An item you include in a scope is visible in the scope in which it was created and in any child scope, unless you explicitly make it private. You can place variables, aliases, functions, or Windows PowerShell drives in one or more scopes.
  • An item that you created within a scope can be changed only in the scope in which it was created, unless you explicitly specify a different scope.

Windows PowerShell Scopes

Scopes in Windows PowerShell have both names and numbers. The named scopes specify an absolute scope. The numbers are relative and reflect the relationship between scopes.

Global: The scope that is in effect when Windows PowerShell starts. Variables and functions that are present when Windows PowerShell starts have been created in the
global scope. This includes automatic variables and preference variables. This also includes the variables, aliases, and functions that are in your Windows PowerShell profiles.

Local: The current scope. The local scope can be the global scope or any other scope.

Script: The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope.

Private: Items in private scope cannot be seen outside of the current scope. You can use private scope to create a private version of an item with the same name in another scope.

Numbered Scopes: You can refer to scopes by name or by a number that describes the relative position of one scope to another. Scope 0 represents the current, or local scope. Scope 1 indicates the immediate parent scope. Scope 2 indicates the parent of the parent scope, and so on. Numbered scopes are useful if you have created many recursive scopes.

By default, variables are available only in the scope in which they are created.

For example, a variable that you create in a function is available only within the function. A variable that you create in a script is available only within the script (unless you dot-source the script, which adds it to the current scope).

You can use a scope modifier to change the default scope of the variable. The following expression creates a variable named “Servers”. The variable has a global scope, even when it is created in a script or function.

PS D:\MyScripts> $global:Servers = "DC1", "DC2", "FileServer"
PS D:\MyScripts>
PS D:\MyScripts> $Servers
DC1
DC2
FileServer

Saving Variables

Variables that you create are available only in the session in which you create them. They are lost when you close your session. To create the variable in every Windows PowerShell session that you start, add the variable to your Windows PowerShell profile. For more information on PowerShell profiles, visit this page.

The Variable cmdlets

Windows PowerShell includes a set of cmdlets that are designed to manage variables. To list all the cmdlets that you can use to work with variables, use the following command:

PS D:\MyScripts> Get-Command -Noun Variable

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Cmdlet          Clear-Variable                                     Microsoft.PowerShell.Utility
Cmdlet          Get-Variable                                       Microsoft.PowerShell.Utility
Cmdlet          New-Variable                                       Microsoft.PowerShell.Utility
Cmdlet          Remove-Variable                                    Microsoft.PowerShell.Utility
Cmdlet          Set-Variable                                       Microsoft.PowerShell.Utility

To get help for these cmdlets, use “Get-Help <cmdlet-name> -Detailed” command.

Back

 



Microsoft Certified | Cisco Certified