Setting environment variables in PowerShell is easy. This post will show you how to create a PowerShell environment variable which is scoped:
- Locally to your current PowerShell session.
- To your user profile and available to all other processes that you execute
- To the machine, and accessible to all processes that run on that system.
Set a locally scoped Environment Variable
To create an environment variable that is local to your current PowerShell session, simply use:
$env:SiteName = 'tachytelic.net'
Then you can check the value of the environment variable with this code:
Get-ChildItem Env:SiteName
This method is fine, but the variable will vanish when the PowerShell process ends.
Set an Environment Variable scoped to the User
To set an environment variable which will be available to all processes that your account runs, use the following:
[System.Environment]::SetEnvironmentVariable('siteName','tachytelic.net',[System.EnvironmentVariableTarget]::User)
Now you can see the variable is set from the Environment variables section of the system properties:
Set an Environment Variable scoped to the Machine
To create an environment variable visible to every process running on the machine:
[System.Environment]::SetEnvironmentVariable('siteName','tachytelic.net',[System.EnvironmentVariableTarget]::Machine)
Note: This command will probably fail unless you run PowerShell as an administrator.
The new PowerShell System environment variable is visible:
It’s quite interesting that the PowerShell environment variables are stored in a drive, which you can access using:
Set-Location Env: Get-ChildItem
For more information on how PowerShell environment variable work, read the Microsoft documentation here.
Richard says
Really useful, thanks
charles a ross says
The latter 2 will only work if you are running admin shell.
Jonathan Tyler says
Hi, your link to additional information at the end of the article does not point to a valid address.
Daniel says
Hi Paul, Thanks for writing this Post. It really helped me to set my variable to the machine scope!
Do you have any advice on how to set a variable with a path that has a space in it? IE: “C:\Program Files\app”
Abdul Mannan Mohammed says
how do you set the user environment variable for all users