Assign Variables in PowerShell

Image Description

Daily PowerShell #37

Daily PowerShell Basics

November 22, 2021

quote Discuss this Article

In this blog post, we’ll look at the basics of assigning variables.

Basic Assignment

The basic assignment uses the $ character in front of the variable name.

$Variable = 123

Assignment using Set-Variable

You can use the Set-Variable cmdlet to set variables.

Set-Variable -Name 'Variable' -Value 123

Variable Scope

You can change the scope of a variable by using the scope prefix.

Global scope is available anywhere in the current PowerShell environment. Script scope is available to the current script file or module.

$Global:Variable = 123
$Script:Variable = 123

Set-Variable -Name Variable -Value 123 -Scope Global
Set-Variable -Name Variable -Value 123 -Scope Script

Set Variables with Complex Names

You can use Set-Variable with complex names. You can also use curly braces and the $ prefix to reference variables with characters such as spaces.

Set-Variable -Name 'This is a variable with spaces' -Value 123
${This is a variable with spaces} = 123

Set Read Only Variables

You can create read only variables with Set-Variable.

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

Set Variable Descriptions

Set-Variable allows you to add descriptions to your variables. You can view variable descriptions with Get-Variable.

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