Using PowerShell to Manage Environment Variables
This page is a basic tutorial on using PowerShell to manage environment variables.
If you are not familiar with Windows env var, see: Windows Environment Variables Tutorial.
Environment Variable for Current Session
# list environment variables dir env: # or gci env:
# show env vars whose name contains “path” Get-ChildItem Env:*path* | format-list
# show value of “path” $env:path
Set or Remove
# sets a env var named myX for current session $env:myX = "alice"
# get value of a env var $env:myX
# deleting a env var from the current session Remove-Item env:myX
# adding path to the path env var $env:path = $env:path + ";C:\Program Files (x86)\ErgoEmacs\hunspell"
View/Set Permament Environment Variables
Permanent env vars are stored in Windows Registry. When PowerShell launches, it reads the registry to get the env vars for the current session. However, it does not update the registry whenever you create or remove a env var using the
env: provider. To manipulate env var in the registry for permanent use, use the .NET object like the following:
# displaying a env var named “myY” of the category “User”. [environment]::GetEnvironmentVariable("myY", "User")
The possible values for the second argument in GetEnvironmentVariable are:
# creates “myY” of category “User”, and set the value to “"la la"” [Environment]::SetEnvironmentVariable("myY", "la la", "User")
[Environment]::SetEnvironmentVariable means calling the .NET object “Environment” and using its method “SetEnvironmentVariable”.
# example of adding a path to PATH [System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";C:\Program Files (x86)\PHP", "Machine")
2018-02-23 Ronald Mout says:
Please be aware that the variable $Env:Path is the merge of system path and user path. Depending on the user who executes this command, the systempath will be poluted with entries from his/her userprofile. You'd better use:
$CurrentPath = (Get-Itemproperty -path 'hklm:\system\currentcontrolset\control\session manager\environment' -Name Path).Path $NewPath = $CurrentPath + ";C:\Program Files (x86)\PHP" Set-ItemProperty -path 'hklm:\system\currentcontrolset\control\session manager\environment' -Name Path -Value $NewPath
# removing a env var from registry [Environment]::SetEnvironmentVariable("myY", $null, "User")
If you want PowerShell to update its env var session from the registry, you can restart PowerShell. Just launch a new
- get-help environment_variables
- get-help about_provider
If you have a question, put $5 at patreon and message me.