Variables in PowerShell are preceded by the dollar symbol ($), for example:
$MyVariable
The name of a variable may contain numbers, letters, and underscores. For example, each of the following is a valid name:
$123 $x $my_variable $variable $varIABle $Path_To_File
Variables are frequently written in either camel case or upper-camel case (also known as pascal case). PowerShell does not enforce any naming convention, nor does it exhibit a convention in any of the automatic variables. For example:
- $myVariable is camel case
- $MyVariable is upper-camel case or pascal case
I suggest making your variable names meaningful so that when you come and visit your script again after a long break, you can identify its purpose. I recommend choosing and maintaining a consistent style in your own code.
It is possible to use more complex variable names using the following notation:
${My Variable} ${My-Variable}
The following notation, where a file path is written as the variable name, allows variables to be stored on the filesystem:
${C:WindowsTempvariable.txt} = "New value"
Inspecting the given file path shows that the variable value has been written there:
PS> Get-Content C:WindowsTempvariable.txt
New value
Variables do not need to be declared prior to use, nor does a variable need to be assigned a specific type, for example:
$itemCount = 7 $dateFormat = "ddMMyyyy" $numbers = @(1, 9, 5, 2) $psProcess = Get-Process -Name PowerShell
It is possible to assign several variables the same value in one statement. For example, this creates two variables, i and j, both with a value of 0:
$i = $j = 0