PowerShell – How to create Variables?

PowerShell allows us to create the variables. We use “$” Symbol to create the variables. Through this Article, we will discuss more about defining the variables and PowerShell command(s) to support defining them.

Create Variables in PowerShell

Let’s take a simple example;

PS C:\> $message = "Hello!"

Here we have defined the variable $message and assigned a value to it. Once the variable is defined with a value, we can use it in our PowerShell scripts.

PS C:\> $message
Hello!

PowerShell provides commands to define and manage the variables to get more control.

The New-Variable cmdlet

This command is used to define the variable. The variable name should be passed through the parameter “-Name“. Otherwise, it prompts to enter the name of the variable.

To assign a value to it; you must pass the value through “-Value” parameter.

PS C:\> New-Variable -Name var -Value 100
PS C:\> $var
100

If the variable already exists, when you attempt to create the same variable using this command; PowerShell will throw the Error. Here is an example:

PS C:\> New-Variable -Name message -Value "Hello!"
New-Variable : A variable with name 'message' already exists.
At line:1 char:1
+ New-Variable -Name message -Value "Hello!"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (message:String) [New-Variable], SessionStateException
    + FullyQualifiedErrorId : VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand

Force to create the Variable

We can still create the variable (even though it already exists); by using the option “-Force”. This option instructs to PowerShell to override the variable. Here, you go;

PS C:\> New-Variable -Name message -Value "Hello, World!"

One thing you need to remember, when defining variables using this command is; you must NOT enter “$” symbol when you give the name of the variable through “-Name” parameter. Otherwise, PowerShell will throw the Error. Here is an example:

PS C:\> New-Variable -Name $var -Value 100
New-Variable : Cannot bind argument to parameter 'Name' because it is an empty string.
At line:1 char:20
+ New-Variable -Name $var -Value 100
+                    ~~~~~~
    + CategoryInfo          : InvalidData: (:) [New-Variable], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.NewVariableCommand

Creating Variables with spaces

This command allows us to create the PowerShell variables with spaces. Spaces in variables are NOT recommended; it creates lot of confusion. Instead you can use underscore (“_”) for more readability.

When you use spaces in variables; you must pass the variable name within quotes. You can use either single (‘) or double (“) quotes. Here is an example:

PS C:\> New-Variable -Name "say hello" -Value "Hello, World!"

Here it creates the variable “say hello” and assigned the value to it.

Accessing data from the Variables

Once the Variable is defined, it is simple to access it by using the symbol “$”. This represents, the variable. We already seen, accessing the variable in top of this Article. Here again;

PS C:\> $var
100

But does it work the same for the variables with spaces? Let’s try to access the one we defined; “say hello”.

PS C:\> $say hello
At line:1 char:6
+ $say hello
+      ~~~~~
Unexpected token 'hello' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

PowerShell throwing the Error when we attempt to access the variable with spaces, in normal way. Let’s try adding our variable in quotes to access it;

PS C:\> $"say hello"
$say hello : The term '$say hello' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.
At line:1 char:1
+ $"say hello"
+ ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: ($say hello:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Again it is throwing the Error. Then how to access the variables with spaces? This is where Get-Variable cmdlet required.

The Get-Variable cmdlet

This command is used to display the data from the variables. To display the content of the variable “$var“, we created; you can pass the variable as an argument to this command. You can pass it directly or through the “-Name” parameter.

PS C:\> Get-Variable -Name var

Name                           Value
----                           -----
var                            100

If the variable name contains spaces, you can include the variable in quotes. Here we will display the content of the variable “say hello”.

PS C:\> Get-Variable -Name "say hello"

Name                           Value
----                           -----
say hello                      Hello, World!

Does it working fine? Yes. But have you noticed this command always displaying the data in particular format?

We do not need this format always. Especially when you use these variables in a script; you need only the value of the variable; NOT the display format. How do we get this? It’s simple; by using “-ValueOnly” parameter, we can inform the command to return the value ONLY. Here, you go!

PS C:\> Get-Variable wow -ValueOnly
WoW! Wonderful!

[..] David

PowerShell – How to create Variables?

2 thoughts on “PowerShell – How to create Variables?

Leave a Reply

Your email address will not be published.

Scroll to top