How to set environment variables on Windows with Powershell

The concern is documenting setting the env variables from powershell instead of via GUI. There is a transient (session-specific), but more importantly, also a non-intuitive and often needed persistent way of doing this.

Pavol Kutaj
1 min readSep 4, 2023

1. transient

  • note that the above method are scoped to the current powershell process

1.1. it is a provider

  • you can use environmental variables like a drive
▶ cd env:
▶ dir

Name Value
---- -----
__COMPAT_LAYER Installer
ALLUSERSPROFILE C:\ProgramData
APPDATA C:\Users\Admin\AppData\Roaming
asl.log Destination=file
ChocolateyInstall C:\ProgramData\chocolatey
  • use set-content $env $value
  • in my case
Set-Content .\CONSUL_HTTP_TOKEN 1111111-1111-111111-1111-111111111111

1.2. just do it directly

  • use the built-in $env
$env:CONSUL_HTTP_TOKEN = 1111111-1111-111111-1111-111111111111

1.3. setting env vars

  • for the machine-level
[Environment]::SetEnvironmentVariable("TestVariableName", "My Value", "Machine")

2. persistent

  • you need to use a deeper .NET mechanisms to make this persistent

2.1. user-scope

[System.Environment]::SetEnvironmentVariable('KEY', 'VALUE', [System.EnvironmentVariableTarget]::User)
  • example
[System.Environment]::SetEnvironmentVariable('ELECTRON_NO_ATTACH_CONSOLE', 'true', [System.EnvironmentVariableTarget]::User)

2.2. machine-scope

[System.Environment]::SetEnvironmentVariable('KEY', 'VALUE', [System.EnvironmentVariableTarget]::Machine)

3. sources

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com