Kae Travis

Use PowerShell to Read and Write Environment Variables

Here we explain how to use PowerShell to read and write environment variables, which exist in the user, process and machine contexts.

We can read and write environment variables in a variety of ways, but the easiest ways to read an environment variable (ComputerName in this example) are as follows:

#option 1
(Get-Item -Path Env:ComputerName).Value
#option 2
$env:ComputerName

Similarly, we can set environment variables like so:

Set-Item -Path Env:\ComputerName -Value "NewComputerName"
$env:ComputerName = "NewComputerName"

But both of these methods only set the environment variable for the current process (i.e the current session). To set it persistently, we can use the .net class to manipulate environment variables. To read we can do the following:

([System.Environment]::GetEnvironmentVariables()).COMPUTERNAME

We can get variables from the different contexts like so:

[System.Environment]::GetEnvironmentVariable('ComputerName','User')
[System.Environment]::GetEnvironmentVariable('ComputerName','Process')
[System.Environment]::GetEnvironmentVariable('ComputerName','Machine')

and set environment variables like so:

[System.Environment]::SetEnvironmentVariable('ComputerName','NewComputerName','User')
[System.Environment]::SetEnvironmentVariable('ComputerName','NewComputerName','Process')
[System.Environment]::SetEnvironmentVariable('ComputerName','NewComputerName','Machine')

You will need to elevate your PowerShell session to be able to set machine environment variables.

Use PowerShell to Read and Write Environment Variables
Use PowerShell to Read and Write Environment Variables

Leave a Reply