[Environment]::GetEnvironmentVariables()
You can list machine specific environment variables or user specific environment variables using this function. The below command lists only computer specific environment variables
[Environment]::GetEnvironmentVariables("Machine")
Likewise, the below command lists only user specific environment variables
[Environment]::GetEnvironmentVariables("User")
Find specific (single) environment variable
Instead of listing all the environment variables, we can use the function “[Environment]::GetEnvironmentVariable” to get the value of specific environment variable.
[Environment]::GetEnvironmentVariable("ComputerName")
The below command gets the current user’s “Temp” directory path.
[Environment]::GetEnvironmentVariable("Temp","User")
Likewise, the below command gets the current computer’s “Temp” directory path.
[Environment]::GetEnvironmentVariable("Temp","Machine")
Get environment variable from Remote machine
We can get an environment variable from remote machine by running the above command using Invoke-Command. Before proceed, we should enable powershell remoting to run remote commands. Check this article : How to enable Powershell Remoting
Syntax of remote powershell command:
Invoke-Command -ComputerName $Target -ScriptBlock { $COMMAND } -Credential $USERNAME
$Target – The name of the computer to connect.
$COMMAND – The powershell command to run in remote computer.
$USERNAME – The user account to run the command as on the remote computer. You will be prompted to enter a password for the username. The Credential parameter is optional one.
The following command gets the name of the remote machine.
Invoke-Command -ComputerName "ESVR1" -ScriptBlock {[Environment]::GetEnvironmentVariable(“ComputerName”)}
The below command gets the “Temp” directory path of the remote computer “ESVR1”.
Invoke-Command -ComputerName "ESVR1" -ScriptBlock {[Environment]::GetEnvironmentVariable(“Temp”,”Machine”)}
The below command gets the “Temp” directory path for the user “Morgan” in the remote machine “ESVR1”.
Invoke-Command -ComputerName "ESVR1" -ScriptBlock {[Environment]::GetEnvironmentVariable(“Temp”,”User”)} -Credential Morgan