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
# show current env vars Get-ChildItem 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")
# 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