Question:
I have the name of an environment variable in a variable and I want to get the value. How do I do that? I’ve tried:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
PS C:\Users\Joe> $v="USERDOMAIN" PS C:\Users\Joe> "$env:$v" At line:1 char:2 + "$env:$v" + ~~~~~ Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive PS C:\Users\Joe> "$env:$($v)" At line:1 char:2 + "$env:$($v)" + ~~~~~ Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive |
Answer:
Two lines
1 2 3 |
$v = "Path" (get-item env:$v).Value |
One line
1 2 |
iex ('$env:' + $x) |