How to expand variable in powershell?
I didn't find expanding expressions in PowerShell, but here's what I found.
# Let's set some varaible
$ComputerName = 'some-value'
# Let's store this variable name
$name = 'ComputerName'
# Get value by `Get-Item`.
(Get-Item variable:$name).Value # throws an exception for undefined variables.
# Get value by `Invoke-Expression`
Invoke-Expression "`$variable:$name"
Invoke-Expression "`$$name"
The same but for environment variables
(Get-Item env:$name).Value # throws an exception for undefined environments.
Invoke-Expression "`$env:$name"
I prefer Get-Item
as it "fails loudly".
And Get-Item
allows to use additional literals during this process, as well as Invoke-Expression
.
I.e. see the Computer
literal below before the $ sign.
$otherName = 'Name'
(Get-Item variable:Computer$otherName).Value
(Get-Item env:Computer$otherName).Value
When you start a string literal with '
(single-quotes), you're creating a verbatim string - that is, every character inside the string is interpreted literally and variable references and expressions won't expand!
Use "
if you want the variable to be expanded:
$var = 'C:'
Get-WmiObject -Class win32_logicaldisk -Filter "DeviceID='$var'"
If your variable name has weird characters, or is followed by a word character, you can qualify the variable name with curly brackets {}
immediately after the $
:
$var = 'C:'
Get-WmiObject -Class win32_logicaldisk -Filter "DeviceID='${var}'"
If, for instance, you're getting data from a file with select-string, the return is a single quote string. If that string contains variables they won't expand. Invoke-Expression can be used if the variable is clean - not mixed in with other text:
$abc = 123
$a = '$abc'
iex $a -> 123
If the variable is part of a path name, this doesn't work. Use $ExecutionContext.InvokeCommand.ExpandString($var)
$path = '$Home/HiMum'
$ExecutionContext.InvokeCommand.ExpandString($path)
-> /home/JoeBlogs/HiMum
You lucky sods on Windows might be able to use Convert-String to change singles to doubles.