Friday, 7 August 2015

Get list of environment variables from Powershell

We can get the list of environment variables using the .NET class [Environment]::. The following command list all the local environment variables.
You can list machine specific environment variables or user specific environment variables using this function. The below command lists only computer specific environment variables
Likewise, the below command lists only user specific environment variables

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.
The below command gets the current user's "Temp" directory path.
Likewise, the below command gets the current computer's "Temp" directory path.

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


No comments:

Post a Comment