PowerShell provides multiple ways to set an environment variable.
Method 1: Using the $env Provider to Set Environment Variable
$env:my_variable = "somevalue"
This script sets an environment variable my_variable
with the value “somevalue” using the $env
provider.
Method 2: Using the [Environment] Class to Set Environment Variable
[Environment]::SetEnvironmentVariable("my_variable", "somevalue", "Machine")
This script sets the environment variable my_variable
with the value “somevalue” and the environment variable scope as “Machine“.
Method 3: Using the Set-Item cmdlet to Set Environment Variable
Set-Item -Path Env:my_variable -Value "somevalue"
This script sets the environment variable my_variable
with the value “somevalue” using the Set-Item
cmdlet in PowerShell.
All these methods set the environment variable.
The following examples show how to use each method in practical application.
Using the $env Provider to Set Environment Variable
The $env
automatic variable allows you to access and modify the environment variables.
This example shows how to set a variable using the $env automatic variable.
$env:RConstant = 8.31453
In this example, the $env
provider sets a variable named “RConstant” by assigning a value using the assignment operator (=).
You can print the constant value using the following script.
(base) PS C:\> $env:RConstant 8.31453
Note, that it only sets the environment variable for the current PowerShell session.
Using the [Environment] Class to Set Environment Variable
You can utilize the static method [SetEnvironmentVariable] from the [Environment] class to set an environment variable.
The following example shows setting an environment variable using the [Environment] class.
[System.Environment]::SetEnvironmentVariable("RConstant", 8.34153, "Machine")
In this example, the SetEnvironmentVariable
method sets the environment variable RConstant with a value of 8.31453. The third parameter specifies the scope ( either “Machine” for all users or “User” for the current user).
Using the Set-Item to Set Environment Variable
Another way to set environment variable is by using the Set-Item
cmdlet with the Env:
drive.
The following example shows how to use the Set-Item cmdlet.
Set-Item -Path Env:RConstant -Value 8.31453
In this example, Set-Item
command sets an environment variable named “RConstant” with the value of 8.31453. This method can persist the environment variable beyond the current session.
Conclusion
I hope the above article on how to set environment variables in PowerShell using different methods is helpful to you.
Remember that, while setting an environment variable at the machine scope, requires administrative privileges.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.