CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

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 a 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 variable is NOT already defined, it defines and changes its 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 a more controlled way.

The Set-Variable cmdlet

This command is used for setting variables in PowerShell in a more controlled way. To set the variable, you need to pass the name of the variable through the “-Name” parameter, and its value through the “-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 also allows us to set multiple variables at a time. This is one of the important features 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.

 

See also, “PowerShell – How to reset Variables (using Clear-Variable)?“.

[..] David

PowerShell – How to set variables?

3 thoughts on “PowerShell – How to set variables?

Leave a Reply

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

Scroll to top