Variables in PowerShell are value that can change. You can identify them easily, as they begin with a dollar sign, and they are able to hold strings, integers, arrays, Booleans, or nothing at all.
Definition
To begin with, there are two ways to assign a variable. First, you can use the equals sign (=)
. This tends to be the preferred way to define, because it is quick and distinctive in a script.
$MyString = "Hello World!" # Any quoted combination of characters
$MyInteger = 1 # Whole numbers, as in arithmetic
$MyDouble = 1.5 # Also known as floating-point numbers
$MyBoolean = $true # True or False. Must be used as variables.
$MyNull = $null # Nothing. Also must be used as a variable.
$MyArray = @("Hello", 1, $true, $MyString) # Arrays hold multiple values
# We can use Get-Type to determine what type of variable is being worked with.
Alternatively, it’s possible to use the Set-Variable cmdlet to create a variable with additional options. I’ve decided not to use any for this example, since this is a simple overview. Feel free to use Get-Help
.
Set-Variable -Name MyVariable -Value "This Variable holds a string."
Get-Variable MyVariable
Afterward, set the variable as null and see how it changes.
$MyVariable = $null
Get-Variable MyVariable
Lastly, remove the variable and see what the value is.
Remove-Variable MyVariable
Get-Variable MyVariable
Using Commands and Methods with Variables
You can also define a variable as a cmdlet output and interact with them in the same way you would, saving keystrokes:
$TodaysDate = Get-Date
Get-Variable TodaysDate | Format-List
$TodaysDate.AddHours(1)
Variables cannot dynamically update. After I grabbed the date, the value will not update unless I redefine the variable. This can be good for setting timestamps or more vague variables like the current day or hour.
Types
Lastly, there are multiple types of variables that can be used in PowerShell.
Computers are always using environment variables to determine capabilities and default settings, which PowerShell can also tap into. For instance, your current folder is defined as $PWD
, the Present Working Directory.
PowerShell uses automation variables to store information about the current environment or system. Examples include $Error, which stores information about the most recent error that occurred, and $Input, which contains the values passed to a script or function through pipeline input.
Finally, preference variables control various settings and options that affect the way PowerShell operates, such as the default output format or the behavior of the Tab key in the PowerShell console. Examples of preference variables include $ConfirmPreference, which determines whether PowerShell prompts the user for confirmation before executing potentially dangerous commands, and $VerbosePreference, which controls detail of verbose output.
Get-Variable
will be your best friend here.