Variables in strings
In PowerShell, variables can be included within any double-quoted string. The value of that variable will expand when the string is created.
For example:
$count = 5
$string = "There are $count items"
Variables will not expand inside single-quoted or literal strings.
Provider-specific values will also expand inside a double-quoted string:
"Computer Name: $env:COMPUTERNAME"
The example above uses a colon to split the provider name, env
, from the variable name, COMPUTERNAME
. If a colon is present after a variable name, PowerShell will always interpret it as a provider name.
In the following example, the first variable in the string ends with a colon, which causes a parser error:
PS> $computerName = $env:COMPUTERNAME
PS> "$ComputerName: Running PS $PSEdition"
ParserError:
Line |
1 | "$ComputerName: Running PS $PSEdition"
| ~~~~~~~~~~~~~~
| Variable reference is not valid...