Friday, 7 August 2015

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.
We can also list only computer specific environment variables or user specific environment variables by using below commands
Instead of listing all the environment variables, we can get the value of specific environment variable by using the function "[Environment]::GetEnvironmentVariable".

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


No comments:

Post a Comment