Powershell Get Environment variable from Remote machine

We can find and list the environment variables using the .NET class [Environment]. The following command list all the environment variables in local machine.

[Environment]::GetEnvironmentVariables()

We can also list only computer specific environment variables or user specific environment variables by using below commands

[Environment]::GetEnvironmentVariables("Machine")
[Environment]::GetEnvironmentVariables("User")

Instead of listing all the environment variables, we can get the value of specific environment variable by using the function “[Environment]::GetEnvironmentVariable“.

[Environment]::GetEnvironmentVariable("ComputerName")

Get Environment variable from Remote machine

We can get an environment variable from remote machine by running the above commands using Invoke-Command. Before proceed, we should enable powershell remoting to run remote commands. Read 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 "ESVR01" -ScriptBlock {[Environment]::GetEnvironmentVariable(“ComputerName”)}

The below command gets the “Temp” directory path of the remote computer “ESVR01”.

Invoke-Command -ComputerName "ESVR01" -ScriptBlock {[Environment]::GetEnvironmentVariable(“Temp”,”Machine”)}

The below command gets the “Temp” directory path for the user “Kevin” in the remote machine “ESVR01”.

Invoke-Command -ComputerName "ESVR01" -ScriptBlock {[Environment]::GetEnvironmentVariable(“Temp”,”User”)} -Credential Kevin
Advertisement

1 thought on “Powershell Get Environment variable from Remote machine”

  1. Hi

    I using the comands from a remote posershell and works fine but I have one big problem.

    I just get the User Enviroment of the active powershell user but I need the enviroment of the currently logged on user

    Reply

Leave a Comment