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)
Sign up to request clarification or add additional context in comments.

6 Comments

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.
I agree with you. But plenty of scenarios allow to do it when no user input allowed
Thanks @JasonShirk do you have an alternative injection-proof solution?
The first example here is safe from injection.
@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.
|
1

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.