4

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:

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

2 Answers 2

12

Two lines

$v = "Path"
(get-item env:$v).Value

One line

iex ('$env:' + $x)
6
  • 3
    iex is a bad idea, e.g. if you have $x = '$(del -re -force c:\; "Path")' (say from an attacker) - then you'll be unhappy you used Invoke-Expression. Aug 14, 2014 at 0:23
  • 1
    I agree with you. But plenty of scenarios allow to do it when no user input allowed
    – Vladmir
    Aug 14, 2014 at 5:33
  • Thanks @JasonShirk do you have an alternative injection-proof solution? Aug 14, 2014 at 7:52
  • 1
    The first example here is safe from injection. Aug 14, 2014 at 17:35
  • 1
    @Vladmir - I know iex is safe for some scenarios, but people learn about it and misuse it so I try to steer people towards safer solutions and there usually are better/safer solutions. Aug 14, 2014 at 17:37
1

To complement Vladimir's helpful answer with a solution that makes direct use of the .NET framework:

$v="USERDOMAIN"
[Environment]::GetEnvironmentVariable($v) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.