Using PowerShell to Manage Environment Variables

Advertise Here

, 2009-07, 2010-06-18

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 Basic Tutorial.

Showing Environment Variables of Current Session

# show current env vars
Get-ChildItem Env:

# show env vars whose name contains “path”
# Get-ChildItem = dir, gci
Get-ChildItem Env:*path* | format-list

Set and Remove Environment Variables of Current Session

# sets a env var named myX for current session
$env:myX = "la la la"

# get value of a env var
$env:myX

# deleting a env var from the current session
Remove-Item env:myX
# adding to a path to the path env var
$env:path = $env:path + ";C:\Program Files (x86)\ErgoEmacs\hunspell"

Setting 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:

# creates “myY” of category “User”, and set the value to “"la la"”
[Environment]::SetEnvironmentVariable("myY", "la la", "User")

The syntax [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")
# displaying a env var named “myY” of the category “User”.
[environment]::GetEnvironmentVariable("myY", "User")

The possible values for the second argument in GetEnvironmentVariable are: "Process", "User", "Machine".

# removing a env var from registry
[Environment]::SetEnvironmentVariable("myY", $null, "User")

Note: If you want PowerShell to update its env var session from the registry, you can restart PowerShell.

Reference

blog comments powered by Disqus