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.
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:
This method is fine, but the variable will vanish when the PowerShell process ends.
To set an environment variable which will be available to all processes that your account runs, use the following:
Now you can see the variable is set from the Environment variables section of the system properties:
To create an environment variable visible to every process running on the 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.