Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of environment variable with powershell

Tags:

powershell

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
like image 328
Mark Allison Avatar asked Dec 11 '22 04:12

Mark Allison


2 Answers

Two lines

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

One line

iex ('$env:' + $x)
like image 174
Vladmir Avatar answered Dec 24 '22 18:12

Vladmir


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

$v="USERDOMAIN"
[Environment]::GetEnvironmentVariable($v) 
like image 22
mklement0 Avatar answered Dec 24 '22 19:12

mklement0