PS: Behavior of Environment Variable Prioritization

Priority handling when there are conflicting and/or same variables at both Machine and User level:

PS C:> $a = [Environment]::GetEnvironmentVariable("Temp","Machine")
PS C:> echo $a
C:WindowsTEMP
PS C:> $a = [Environment]::GetEnvironmentVariable("Temp","User")
PS C:> echo $a
C:UsersgovardhanAppDataLocalTemp
PS C:> $a = [Environment]::GetEnvironmentVariable("Temp")
PS C:> echo $a
C:UsersGOVARD~1AppDataLocalTemp

PS C:>

In case of a conflict, Windows and thus PS refers to User level variable under a user session.

 

The weird behavior is sometimes, you environment variables aren’t read as either type “User” or “Machine” but can be read without any type specification.

PS C:> $a = [Environment]::GetEnvironmentVariable("appdata","User")
PS C:> echo $a
PS C:> $a = [Environment]::GetEnvironmentVariable("appdata","Machine")
PS C:> echo $a
PS C:> $a = [Environment]::GetEnvironmentVariable("appdata")
PS C:> echo $a
C:UsersgovardhanAppDataRoaming
PS C:>

 

 

 

0 thoughts on “PS: Behavior of Environment Variable Prioritization

  1. How can i get use

    [Environment]::GetEnvironmentVariable(“Temp”,”Machine”)

    to get the setting from a remote server?

    1. You can always use Invoke-command for remtoe execution as shown below:

      Invoke-command -computername -ScriptBlock {Write-Host [Environment]::GetEnvironmentVariable(“Temp”,”Machine”)}

  2. Hmmm it didn’t work in my powershell script. Would you be interested to look at my script? let me know and i’ll post a download link

    1. #$MyReport += Invoke-Command -ScriptBlock -ComputerName $Target {[Environment]::GetEnvironmentVariable(“Temp”,”Machine”)}

      Should be:
      #$MyReport += Invoke-Command -ComputerName $Target -ScriptBlock {[Environment]::GetEnvironmentVariable(“Temp”,”Machine”)}
      OR
      #$MyReport += Invoke-Command -ComputerName $Target {[Environment]::GetEnvironmentVariable(“Temp”,”Machine”)}

      Test out just this command to verify that it’s getting intended data (i.e., System environment variable %temp%) from the remote system. If things work fine you can have this coded in your script.

  3. Try both and it does not run 🙁

    Object reference not set to an instance of an object. (Invoke-Command) At line: 366 char: 30

Leave a Reply

Your email address will not be published. Required fields are marked *