We use variables to store all types of values. PowerShell is an Object Oriented Scripting Language. PowerShell works with objects, and these objects can have attributes and methods. An attribute is a property or a description.
A variable is a unit of memory in which values are stored. In PowerShell, variables are represented by text strings that begin with a dollar sign ($
), such as $a
, $b
, or $my_var
. Variable names aren’t case-sensitive, and can include spaces and special characters. Yes! you read it right. can include spaces and special characters. But, variable names that include special characters and spaces are difficult to use and should be avoided.
We need not to define the type of variable. PowerShell automatically decides the type of variable.
Working with variables
To get a list of all the variables in your PowerShell session, type Get-Variable
.
We can assign values manually. For example:
$name = "James" $names = "Robert", "John", "Mary"
We can use variables to store result of a command.
For example:
$Processes = Get-Process $Services = Get-Service
To display the value of a variable, type the variable name, preceded by a dollar sign ($
).
PS C:\> $name James PS C:\> $names Robert John Mary PS C:\> $Processes Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 381 28 16928 39288 0.13 20672 1 ApplicationFrameHost 1315 116 64912 107460 123.41 18036 1 AppMarket 130 10 1704 6856 5192 0 armsvc . . . 279 14 3776 10388 13800 0 WUDFHost 248 14 3660 9260 14244 0 WUDFHost 913 56 56568 31100 0.45 13964 1 YourPhone PS C:\>
To change the value of a variable, assign a new value to the variable.
To delete the value of a variable, use the Clear-Variable
cmdlet or change the value to $null
. To delete the variable, use Remove-Variable or Remove-Item.
Clear-Variable -Name my_var
Remove-Variable -Name my_var