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
-Filter "DeviceID='$var'"
(notice the double-quotes around the filter string) – Location{}
around the variable, which will surely make the query return nothing – Location{}
. Now it works. I can't believe this did not happen to be one of the 1000 things I've tried, because for sure I tried'DeviceID="$var"'
, and I thought that' '
and" "
are the same, but each one goes inside the other. Still, do you know why the{}
didn't work? I used{$var}
inside strings a lot of times, and just now it didn't work. Also, you can add your solution as an answer. – Goodnatured${var}
would have worked, and resulted in the stringC:
, but{$var}
would result in the string{C:}
– Location