Variable Management in Powershell

There are 2 types of variables in Powershell.

  1. Environment
  2. Shell Variables

Environment Variables in Powershell

You can use “gci Env:” command to view all environment variables in Powershell.

To view specific variable, you can use below command.

> echo $Env:Path

Creating Powershell variables

You can create variables using below syntax.

> $var1=”value”

Below example shows how to create a variable in Powershell.

variables-in-powershell
variables-in-powershell

Viewing Powershell Variables

To view shell variables, you can use dir (gci, ls, Get-ChildItem) command.
> dir variable:

Deleting Powershell Variables
To delete the variable, you can use rm (Remove-Item, del, erase, ri, rd) command
rm Variable:\<variable-name>

Storing the output of command in variable

Below command will store all processes running in the system
$processInfo=Get-Process

To get the names of all processes, you can use below syntax.

echo $processInfo.name

To get the first process in collection, you can use below syntax.
echo $processInfo[0]

Getting type and members supported by the variable

To know the data type of a variable, you can use getType() method. We can also get the methods supported by variable using “get-member” method.

getting-type-and-members-of-a-variable
getting-type-and-members-of-a-variable

Casting variables

Below image shows how you can cast the variables in Powershell.

casting-the-variables
casting-the-variables

We have below commands to work with variables in Powershell.

  1. New-Variable : This command creates a new variable.
  2. Set-Variable : This command assigns new value to the variable.
  3. Get-Variable : This command shows the value of the given variable. If you do not specify any variable, all variables will be displayed with their values.
  4. Clear-Variable : This command clears the value of a variable.
  5. Remove-Variable : This command removes the variable. If you try to access this removed variable, you will get error.

Here is the image showing these commands in action.

variable-management-in-powershell

variable-management-in-Powershell

 

You may also like...