我有一个脚本来查询远程Windows服务器列表,以检索我创建的环境变量的值。
当我打印所有变量时,我可以看到该变量确实存在:
变量本身是由
当我打印所有变量时,我可以看到该变量确实存在:
$EnvObj
:try
{
$Name="MY_VAR"
$VerbosePreference="Continue"
# Read a list of server names
$file = New-Object System.IO.StreamReader -Arg "C:\Users\foo\Documents\test.txt"
while ($Computer = $file.ReadLine())
{
if(!(Test-Connection -ComputerName $Computer -Count 1 -quiet))
{
Write-Verbose "$Computer is not online"
Continue
}
try
{
$EnvObj = @(Get-WMIObject -Class Win32_Environment -ComputerName $Computer -EA Stop)
if(!$EnvObj)
{
Write-Verbose "$Computer returned empty list of environment variables"
Continue
}
if($Name)
{
Write-Verbose "Looking for environment variable with the name $name"
$Env = $EnvObj | Where-Object {$_.Name -eq $Name}
# None of these work but printing $EnvObj shows that $Name ("MY_VAR") is there:
$res=[environment]::GetEnvironmentVariable($Name, "Process")
$res1=[environment]::GetEnvironmentVariable($Name, "User")
$res2=[environment]::GetEnvironmentVariable($Name, "Machine")
$res4=$Env:Name
if(!$Env)
{
Write-Verbose "$Computer has no environment variable with name $Name"
Continue
}
}
else
{
Write-Verbose "No environment variable specified. Listing all"
$EnvObj # shows that the requested environment variable is present
}
}
catch
{
Write-Verbose "Error occurred while querying $Computer. $_"
Continue
}
}
}
finally
{
$file.close()
}
变量本身是由
<SYSTEM>
所拥有的:VariableValue Name UserName
------------- ---- --------
1234 MY_VAR <SYSTEM>
但是当我尝试使用任何可能的枚举来检索它时,它都没有返回任何结果:
这些都不起作用,但打印$EnvObj
显示$Name("MY_VAR")
在其中:
# .Net way
$res=[environment]::GetEnvironmentVariable($Name, "Process")
$res1=[environment]::GetEnvironmentVariable($Name, "User")
$res2=[environment]::GetEnvironmentVariable($Name, "Machine")
# PS Way
$res4=$Env:Name
尽管我可以打印出$EnvObj
对象并看到$Name
确实存在,但是为什么会出现问题呢?
$env
,当您使用$ENV:Name
时,它是一个特殊的变量,在ENV:
PSDrive 中查找名为Name
的项。更改变量名称并重试。 - Eris$val = $EnvObj | select -property MY_VAR
返回@{MY_VAR=}
,但实际上没有任何值。 - Pat Mustard$EnvLookup.VariableValue
。 - Jan Chrbolka