Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

#10 PowerShell Learning: Variables in Windows PowerShell

August 14, 2023
in Blog, PowerShell Learning
0
ADVERTISEMENT

Table of Contents

What is Variable?

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

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.

  • 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.
  • 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.
  • 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 C:\> $firsName = 'Chris'
PS C:\> $lastName = 'Nguyen'

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 C:\> Get-ChildItem Variable:

Name                           Value                                                   
----                           -----                                                   
$                              Variable:                                               
?                              True                                                    
^                              Get-ChildItem                                            
false                          False                                                   
firsName                       Chris                                                   
FormatEnumerationLimit         4                                                       
HOME                           C:\Users\admin                                          
Host                           System.Management.Automation.Internal.Host.InternalHost 
InformationPreference          SilentlyContinue                                        
input                          System.Collections.ArrayList+ArrayListEnumeratorSimple  
LASTEXITCODE                   0                                                       
lastName                       Nguyen                                                  
MaximumAliasCount              4096 

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

PS C:\> Get-Variable

Name                           Value
----                           -----
$                              cls
?                              True
^                              cls

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.

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

PS C:\> $svc = Get-Service | Select -First 5
PS C:\> $svc

Status   Name               DisplayName
------   ----               -----------
Stopped  AarSvc_c2fc5c      Agent Activation Runtime_c2fc5c
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Software Monitor Service
Stopped  AJRouter           AllJoyn Router Service

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 C:\> $firstName
Chris
PS C:\> $firstName = "Anna"
PS C:\> $firstName
Anna

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 C:\> Clear-Variable -Name FirstName
PS C:\> $firstName
PS C:\>

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

PS C:\> Remove-Variable -Name FirstName
PS C:\> Remove-Item -Path Variable:LastName
PS C:\> $firstName
PS C:\>

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.

Example about PowerShell variables:

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

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

PS C:\> $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 C:\> [int]$a = 10
PS C:\> [string]$name = "John"
PS C:\> [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 C:\> [int]$a = 10
PS C:\> $a = "Hello"
Cannot convert value "Hello" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ $a = "Hello"
+ ~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], 
    + FullyQualifiedErrorId : RuntimeException

PowerShell tried to convert  value Hello 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 C:\> $b
name
PS C:\> $name = "10"
PS C:\> $name
10

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 C:\> $PSHOME
C:\Windows\System32\WindowsPowerShell\v1.0
PS C:\> "$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 C:\> '$pshome'
$pshome

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

PS C:\> 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 C:\> ${My Var} = "apple", "orange", "mango"

PS C:\> ${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 C:\> ${My `{Var`} is} = "Hello World!"

PS C:\> ${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.

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 C:\> $global:Servers = "DC1", "DC2", "FileServer"

PS C:\> $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 C:\> Get-Command -Noun variable

CommandType Name            Version Source
----------- ----            ------- ------
Cmdlet      Clear-Variable  3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Get-Variable    3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      New-Variable    3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Remove-Variable 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Set-Variable    3.1.0.0 Microsoft.PowerShell.Utility

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

5/5 - (1 vote)
Previous Post

#9 PowerShell Learning: Manage Processes using PowerShell

Next Post

#11 PowerShell Learning: Arrays in Windows PowerShell

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory