This post will illustrate the usage of the “New-Variable” cmdlet in PowerShell.
How to Use the New-Variable (Microsoft.PowerShell.Utility) Cmdlet in PowerShell?
In order to create a new variable, first, use the “New-Variable” cmdlet. Then, use the “-Name” parameter and assign it the variable.
To learn further about using the “New-Variable” cmdlet, overview the practical examples below.
Example 1: Use the “New-Variable” Cmdlet to Create a New Variable
First, use the cmdlet “New-Variable”. Then, place the “-Name” parameter and specify the variable that you need to create:
Example 2: Use the “New-Variable” Cmdlet to Create a Variable and Specify it as a Value
Initially, use the “-Value” parameter and assign it a value while creating a variable:
Let’s execute the newly created variable to check whether the value was assigned to a variable or not:
Example 3: Utilize the Cmdlet “New-Variable” to Create a Private Variable
Use the “-Visibility” parameter and assign it the “Private” value to create a private variable:
To check whether a particular variable is private or public, execute the variable:
It can be observed that the executed variable is private:
Example 4: Use the “New-Variable” Cmdlet to Create a Variable With ReadOnly Option
To create a variable with the “ReadOnly” option, simply use the “-Option” parameter and assign it the “ReadOnly” value:
Now, create another variable with the same name but with a different value to check whether the “ReadOnly” variable was created or not:
As it can be observed that the new variable was not created, which confirms that the “ReadOnly” option variable was created successfully:
That’s it! We have compiled the usage of the “New-Variable” cmdlet in PowerShell.
Conclusion
The “New-Variable” cmdlet creates a new variable in PowerShell. While creating a variable, values can also be assigned to it. However, assigned values can be altered after the creation of a variable. This guide demonstrated PowerShell’s “New-Variable” cmdlet.