Variables in windows powershell

There are 2 types of variables in Powershell.
  • Environment
  • 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.

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.

Casting variables

Below image shows how you can cast the variables in Powershell.We have below commands to work with variables in Powershell.
  • New-Variable : This command creates a new variable.
  • Set-Variable : This command assigns new value to the variable.
  • 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.
  • Clear-Variable : This command clears the value of a variable.
  • 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.

Web development and Automation testing

solutions delivered!!