使用PowerShell返回环境变量的值

时间:2014-08-13 11:29:23

标签: powershell

我在变量中有一个环境变量的名称,我想得到这个值。我怎么做?我试过了:

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

3 个答案:

答案 0 :(得分:7)

两行

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

一行

iex ('$env:' + $x)

答案 1 :(得分:1)

使用直接使用.NET框架的解决方案来补充Vladimir's helpful answer

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

答案 2 :(得分:0)

我相信你可以省略引号:

$v = "USERDOMAIN"
$env:$v
相关问题