Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用powershell返回环境变量的值_Powershell - Fatal编程技术网

使用powershell返回环境变量的值

使用powershell返回环境变量的值,powershell,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 ${}

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

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
两行

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

iex ('$env:' + $x)
要补充直接使用.NET framework的解决方案,请执行以下操作:

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

iex是个坏主意,例如,如果你有$x='$(del-re-force c:\;“Path”)(比如说来自攻击者),那么你会对使用调用表达式感到不高兴。我同意你的看法。但是很多场景允许在不允许用户输入的情况下执行此操作谢谢@JasonShirk您有其他防注射解决方案吗?这里的第一个示例是安全的,不允许注射。@Vladmir-我知道iex在某些场景下是安全的,但是人们了解它并滥用它,所以我试图引导人们使用更安全的解决方案,通常会有更好/更安全的解决方案。