I have a script to query a list of remote windows servers to retrieve the value of an Environment Variable I have created.
I can see that the variable is indeed there because I can see it when I print all variables: $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()
}
The variable itself is owned by <SYSTEM>:
VariableValue Name UserName
------------- ---- --------
1234 MY_VAR <SYSTEM>
But when I try to retrieve it with any of the possible enumerations, it just returns nothing:
None of these work but printing $EnvObj shows that $Name ("MY_VAR") is there:
# .Net way
$res=[environment]::GetEnvironmentVariable($Name, "Process")
$res1=[environment]::GetEnvironmentVariable($Name, "User")
$res2=[environment]::GetEnvironmentVariable($Name, "Machine")
# PS Way
$res4=$Env:Name
... even though when I print the $EnvObj object I can see that $Name is definitely there.
What is wrong?
[environment]::GetEnvironmentVariable...are looking at the local PC not remote. What is in your$Envvariable?$Envhas the data I'm after but when I request it:$val = $Env:Nameit just returns empty. From what I've read this is the correct way to retrieve the data.$val = $Env.Namehas the same result... I've been going off this: technet.microsoft.com/en-us/library/ff730964.aspx$env, when you use$ENV:Nameit is a special variable looking in the PSDrive ofENV:for an item calledName. Change the variable name and try again.