PowerShell – How to set variables?

Once we define the variables, we can alter the content of the variables anytime. Through this Article, we are going to discuss different ways to set the content of the variables.

Setting Variables in PowerShell

We can assign the values to the variables when we define them. We can also change the values whenever needed. Let’s look at simple example, where we assign or change the value of the variable;

PS C:\> $rocket = "Falcon Heavy Rocket"

Here we use the assignment operator “=” to change the value of the variable $rocket. If the variables is NOT already defined, it defines and change it’s value.

We can’t set the variables sometimes; for example, for read-only and constant variables, we can’t alter the content of the Variables.

PowerShell provides Set-Variable command to alter the content of the variables in more controlled way.

The Set-Variable cmdlet

This command is used for setting variables in PowerShell in more controlled way. To set the variable, you need to pass the name of the variable through “-Name” parameter, and it’s value through “-Value” parameter.

PS C:\> Set-Variable -Name rocket_type -Value "Plasma Rocket"

Here we set the variable to the specified value. If the variable is NOT created already; it creates the variable and set the value to it.

Setting multiple Variables at a time

Set-Variable cmdlet is also allows us to set multiple variables at a time. This is one of the important feature of this command.

PS C:\> Set-Variable -Name ("var1", "var2", "var3", "var4") -Value 100

Here it sets the value 100 to all the variables listed in the “-Name” parameter.

[..] David

PowerShell – How to set variables?

2 thoughts on “PowerShell – How to set variables?

Leave a Reply

Your email address will not be published.

Scroll to top