A Quick Guide to Set Variables in PowerShell

Variables are the bread and butter of any programming language. And PowerShell is no exception. Variables allow you to store data, reference it later, and even pass it between scripts and functions. Simply put, they supercharge your PowerShell code. Knowing when and how to declare and initialize variables is key to writing clean, modular PowerShell scripts. PowerShell provides a simple yet powerful way to create and manage variables using the Set-Variable cmdlet. Understanding how to use Set-Variable is key for anyone looking to get started with PowerShell scripting and command-line automation.

In this post, I’ll cover everything you need to know about setting variables in PowerShell. You’ll learn:

  • The basic syntax for initializing variables
  • Different ways to assign values and objects
  • When to use simple assignments vs. Set-Variable
  • How to set variables with specific scopes
  • Common pitfalls to avoid
  • Best practices to use variables effectively

Whether you’re new to PowerShell or have some experience, this guide will help take your variable skills to the next level. So read on to learn how to declare, set, and use variables like a pro!

Introduction to PowerShell Variables

Variables are a critical component of PowerShell scripts, allowing you to store data for use throughout your script. The use of variables in PowerShell allows you to store and manipulate data efficiently, making your PowerShell scripting more dynamic and flexible. By assigning values to variables, you can reuse them throughout your code, saving time and resources. PowerShell variables come in three types: scalar, array, and hash table. Scalar variables store a single value, whereas array variables store multiple values, and hash table variables store key-value pairs.

PowerShell allows for different types of variables, including string, integer, array, and many more. Additionally, there are automatic variables created by PowerShell, preference variables for user preferences, and environment variables for system-level information.

Understanding the Set-Variable Cmdlet

The Set-Variable cmdlet is a built-in PowerShell command that allows you to create new variables, or change the value of existing ones, and control the scope and visibility of variables. This cmdlet is especially useful when you need to assign a specific value to a variable or change the existing value of a variable in PowerShell. The syntax for Set-Variable cmdlet is:

[-Name] <String> 
[[-Value] <Object>] 
[-Scope <String>] 
[-Option {None | ReadOnly | Constant | Private | AllScope}]
[-Visibility {Public | Private}] 
[-Include <String[]>]
[-Exclude <String[]>] 
[-Description <String>] 
[-WhatIf] [-Confirm] [<CommonParameters>]

Here’s a list of some of the important parameters for the Set-Variable cmdlet in PowerShell:

-NameSpecifies the name of the variable. Required for the cmdlet.
-ValueSpecifies the value assigned to the variable.
-ScopeDefines the scope of the variable (e.g., Global, Local, Script).
-OptionSets additional attributes for the variable (e.g., ReadOnly, Private).
-ForceForces the command to overwrite an existing read-only variable.
-DescriptionAdds a description for the variable.
-VisibilitySets the visibility of the variable (Public or Private).

Assignment using Set-Variable in PowerShell

The Set-Variable cmdlet has the following syntax to set variables in PowerShell. It allows you to assign a value to a variable using a more explicit syntax.

Set-Variable -Name <variable-Name> -Value <variable-value>

To change the value of an existing variable, pass the variable name to the -Name and value to the -value parameters. For example, to change the value of $myVar to 20, you would use the following command:

Set-Variable -Name myVar -Value 20

This will overwrite the current value stored in $myVar with “20”. You can also pass a variable to the -Value parameter to set another variable’s value:

$var1 = "First Value" 
Set-Variable -Name var2 -Value $var1

Now $var2 contains the value from $var1.

What Happens If the Variable Doesn’t Exist?

If you try to change the value of a non-existent variable, PowerShell will create it for you automatically. For example, this creates a new variable $myNewVar and sets the value to “New Variable value” even though $myNewVar didn’t exist before:

Set-Variable -Name myNewVar -Value "New variable value"

This is useful for scenarios where you want to change a value but aren’t sure if the variable exists already.

Setting Variables in PowerShell using Assignment Operator

The easiest way to set a variable in PowerShell is to use the assignment operator: In PowerShell, variables are created and assigned values using the “$” symbol followed by the variable name and then the assignment operator (=). For example, to assign the value “123” to a variable named “myVar”, you would use the following command:

$myVar = 123

To set multiple variables in one line, separate them with semicolons:

$ComputerName = "Server01"; $UserName = "jdoe"

Here is another example of setting multiple variables:

# Same value
$i = $j = $k = 0

# Multiple values
$number, $color, $bool = 25, "red", $false

Once assigned, you can access the value of the variable simply by referencing its name. To display the value of a variable, you can use the Write-Output cmdlet:

Write-Output $myVar

You can also use the Write-Host cmdlet to display the value of a variable:

Write-Host "The value of myVar is: $myVar"

Should I Use Set-Variable or $myVar = “value”?

In PowerShell, you will often see variables created and assigned values simply by doing the following:

$myVar = "Hello"

So when should you use Set-Variable versus this basic approach? The key difference is Set-Variable allows you to set additional options when creating the variable, like the scope. It also enables you to change an existing variable’s value. For simple cases where you just want to create a variable and assign a value, using $myVar = "value" works fine. Overall, Set-Variable provides more control.

While the = operator is the most common method to assign a value to a variable, you can also use the += and -= operators for incrementing or decrementing variables, among other things.

Examples of setting variables in PowerShell

Setting variables in PowerShell can be done in various ways. Here are a few examples:

Example 1: Assigning a string value to a variable

$myString = "Hello, PowerShell!"

Example 2: Assigning a number value to a variable

$myNumber = 42

Example 3: Assigning the output of a command to a variable

$myOutput = Get-Process

Example 4: Creating Array Variables

The Set-Variable cmdlet allows you to create array and hash table data structures as well. You can define an array variable:

Set-Variable -Name myArray -Value 1,2,3,4

Now $myArray contains an array. This provides a quick way to create objects as needed in PowerShell.

Example 5: Assigning hash table variable

$Settings = @{
  ComputerName = "Server01"
  UserName = "jdoe"
  ErrorActionPreference = "Stop"

#Another way
New-Variable -Name myHashTable -Value @{Key1="Value1";Key2="Value2"}

Setting the Data Type of a Variable

By default, PowerShell variables are typeless and can contain any type of data. However, by setting the data type, you enforce that the variable can only hold values of that specific type. The syntax to set the data type of a variable in PowerShell is as follows:

[data_type]$VariableName = value

Here are some examples that demonstrate how to set the data type for various variables.

[int]$myInt = 5
[string]$myString = "Hello, World!"
[bool]$myBool = $true
[datetime]$myDate = Get-Date

This is useful when you need an int vs. string vs. other specific data types. To get the data type of a variable, use: $Variable.GetType().Name

Listing variables in PowerShell

To list all the variables in PowerShell, you can use the “Get-Variable” cmdlet. For example:


This will display a list of all the variables currently defined in the PowerShell session. You can also use the built-in PowerShell drive “Variable:” to get all variables.

Set-Location Variable:


To retrieve the value of a specific variable, you can use the variable name preceded by the “$” symbol. For example:


This will display the value stored in the variable “myVariable”.

Powershell Get-Variable

Setting the Scope of a Variable in PowerShell

The scope of a variable refers to the context in which the variable is visible and can be used. Variables in PowerShell can be classified as local, global, or script-specific. By default, a created variable has a local scope, meaning it is only available in the current scope of the PowerShell session.

Scope determines the visibility and lifetime of a variable. Here are some examples of using Set-Variable to configure a variable’s scope explicitly.

The available scopes are:

  • Global – Available everywhere
  • Local – Only available in the current scope or function
  • Script – Available only in the current script
  • Private – Only available in the current scope and scopes nested inside it

By default, the Set-Variable creates a variable with local scope. That means it will only be available in the current scope. You can use the -Scope parameter to change this:

Create a private variable

The private scope prevents a variable from being overwritten or changed outside of the defining scope. This protects the integrity of the variable’s value in that particular scope. Private variables are commonly used inside functions to temporarily store data that you don’t want to persist after the function exits.

Set-Variable -Name myPrivate -Value 1 -Scope Private

Understanding scope is important, especially when writing PowerShell scripts that call functions or contain advanced logic.

Set Variable’s visibility:

By default, variables are public. The private variable can be accessed only by the scripts with the required permissions, but they won’t be visible to the user.

Set-Variable -Name "myHiddenVar" -Visibility Private

The variable vith “Private” visibility can only be accessed and changed from within the scope where it’s defined. Even if you are within a child scope, you won’t be able to access a private variable from a parent scope. This differs from the -Scope parameter, which determines where a variable exists; the -Visibility parameter controls how it can be interacted with once it’s been created.

Understand public vs. private variables

Public variables: Variables that are declared without any scope modifier are public by default. Public variables are accessible everywhere in the current scope and child scopes. For example:

$myVar = "Hello"

Private variables: Variables declared with the private scope modifier are private. Private variables are only accessible in the current scope, not in any child scopes. For example:

$private:myPrivateVar = "Private"

Or Implicitly use:

function MyFunction {
    $MyPrivateVariable = "I am private within MyFunction."

So, in summary:

  • Public: Accessible in current and child scopes
  • Private: Only accessible in the current scope
  • Use Get-Variable to access private variables from child scopes

Global Variables in PowerShell

By default, variables in PowerShell are local to the scope in which they are defined. However, you can create global variables that are accessible from any scope within your script. To create a global variable, you use the New-Variable cmdlet with the -Scope parameter set to Global:

New-Variable -Name myGlobalVar -Value "Hello, world!" -Scope Global

You can also declare a global variable using “$global:VariableName” scope identifier.

$global:username = "Admin"

To access a global variable from any scope within your script, you can use the $Global: prefix:

Write-Host $Global:myGlobalVar

How to Make a Variable Read-Only?

Sometimes, you may want to create read-only variables that cannot be changed after they are set. This can be useful when you want to protect the integrity of the data stored in the variable. To create a read-only variable, you can use the -Option parameter of Set-Variable with the value “ReadOnly”. Here’s an example:

Set-Variable -Name 'Variable' -Value 123 -Option ReadOnly

The above command creates a read-only variable named “Variable” with the value “123”. Once set, the variable’s value cannot be changed unless the -Force parameter is used.

Constant: Variables with the constant option can’t be modified or deleted. To set the options for a variable, you can use the -Option parameter followed by the “desired “constant” option. For example:

Set-Variable -Name 'Variable' -Value 123 -Option Constant

The above command sets the options for the “Variable” variable to Constant.

Clearing variables in PowerShell

To clear the value of a variable in PowerShell, you can use the “Clear-Variable” cmdlet followed by the variable name. You can clear a variable using Remove-Variable or simply set it to $null. For example:

Clear-Variable -Name myVariable

This will remove the value stored in the variable “myVariable”. Similarly, you can clear multiple variables using wildcards as:

Clear-Variable -Name myVar*

To clear all variables in PowerShell, you can simply close and reopen the PowerShell console or PowerShell ISE. You can also assign $null to the variable value to clear its value.

Deleting variables in PowerShell

In addition to clearing variables, you can also delete variables in PowerShell using the “Remove-Variable” cmdlet. This cmdlet permanently removes the variable from memory. For example:

Remove-Variable -Name age

This will remove the variable “age” from your session.

Set Variable Descriptions

It is a good practice to provide descriptions for your variables to document their purpose and usage. Descriptions can help other scripters understand the intent of the variable and use it correctly.

To add a description to a variable, you can use the -Description parameter of Set-Variable. Here’s an example:

Set-Variable -Name 'Variable' -Value 123 -Description 'This variable has a description'

The above command sets the value of the variable named “Variable” to “123” and adds a description to it.

To view the description of a variable, you can use the Get-Variable cmdlet. For example:

Get-Variable -Name 'Variable'

This will display the variable’s name, value, and description.

Setting Environment Variables through PowerShell

Environment variables provide a way to dynamically configure settings for PowerShell and other programs. To set an environment variable in PowerShell, use the Set-Item cmdlet in the Env: drive like so. For example, let’s assume you have a folder called Scripts where you store all your utility scripts, and you want to add this folder to your system’s PATH so that you can run these scripts from anywhere.

[Environment]::SetEnvironmentVariable("PATH", "$($env:PATH);C:\Scripts", [EnvironmentVariableTarget]::User)

More info here: How to Set Environment Variables using PowerShell?

PowerShell Variable Pitfalls to Avoid

When working with variables in PowerShell, there are also several pitfalls to avoid:

  1. Overwriting variables: Be careful not to overwrite the value of a variable accidentally. This can lead to unexpected results in your script.
  2. Using global variables excessively: As mentioned earlier, global variables can make your code harder to maintain and debug. Use them sparingly.
  3. Not initializing variables: Failing to initialize a variable can lead to errors in your script.

Best Practices for Setting and Managing Variables in PowerShell

When working with variables in PowerShell, there are several best practices to keep in mind:

  1. Use descriptive variable names: Choose variable names that are meaningful and descriptive. This makes it easier to understand the purpose of the variable when reading your script.
  2. Use consistent naming conventions: Use a consistent naming convention for your variables to make your code easier to read and maintain. Avoid using special characters and start with a letter. Also, PowerShell is case-insensitive, but it’s a good practice to stick to a specific case for readability.
  3. Initialize variables: Always initialize variables with a default value, even if you plan to change it later in your script.
  4. Use the right type: Use the appropriate variable type for your data to ensure that your script runs efficiently and avoids errors.
  5. Avoid global variables: Global variables can make your code harder to debug and maintain. Whenever possible, use local variables instead.
  6. To effectively manage variables in PowerShell, it is important to follow some best practices:
  7. Clear variables when no longer needed: Clearing variables when they are no longer needed frees up memory and prevents potential confusion or errors.
  8. Avoid global variables: Global variables can cause unexpected side effects and make your code harder to debug. Whenever possible, limit the scope of your variables to the specific functions or scripts where they are needed.
  9. Use proper variable scoping: PowerShell supports different variable scopes, such as global, script, local, and private. Understanding and using the appropriate scope for your variables can help prevent naming conflicts and improve code readability.


  • Variables in PowerShell can store and manipulate data to make your scripts more flexible.
  • Use Set-Variable cmdlet to create or change the value of a variable.
  • Understand the scope of your variables: local, global, or script-specific.
  • Assign default values and set variables as read-only or private as needed.
  • Leverage environment and automatic variables for more dynamic scripting.

This guide aimed to be a comprehensive resource for mastering variables in PowerShell. Utilizing variables properly will not only make your scripts more efficient but also easier to read and manage.

Wrapping up

Variables are a fundamental concept in PowerShell, allowing you to store and manipulate data within your scripts. In this comprehensive guide, we have explored the basics of working with variables in PowerShell. We learned how to declare, set, assign, list, clear, and delete variables in PowerShell. Additionally, we discussed various aspects of setting variables in PowerShell, including basic assignment, using the Set-Variable cmdlet, variable scope, read-only variables, variable descriptions, options, and best practices.

Remember to use descriptive variable names, initialize your variables, and choose the appropriate variable type for your data. By mastering these techniques, you will be able to leverage the power of PowerShell variables to enhance your scripting and automation tasks. Happy PowerShell scripting!

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

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