How to Set environment variables using PowerShell?


To set the environmental variable using PowerShell you need to use the assignment operator (=). If the variable already exists then you can use the += operator to append the value, otherwise, a new environment variable will be created.

For example, there is no AZURE_RESOURCE_GROUP environment variable that exists in the system. We can create it as below.

$env:AZURE_RESOURCE_GROUP = 'MyTestResourceGroup'

Now when you check the environment variables in the system, you will get the above variable name.

PS C:\Windows\system32> dir env:
Name                            Value
----                            -----
ALLUSERSPROFILE                 C:\ProgramData
APPDATA                         C:\Users\delta\AppData\Roaming
AZURE_RESOURCE_GROUP            MyTestResourceGroup
CommonProgramFiles              C:\Program Files\Common Files
CommonProgramFiles(x86)         C:\Program Files (x86)\Common Files
CommonProgramW6432              C:\Program Files\Common Files
COMPUTERNAME                    TEST1-WIN2K12
ComSpec                         C:\Windows\system32\cmd.exe

If you have another resource group and if you need to add to the same environment variable then as mentioned earlier use += operator and separate value with a semicolon (;).

$env:AZURE_RESOURCE_GROUP = ';MyTestResourceGroup2'
PS C:\Windows\system32> $env:AZURE_RESOURCE_GROUP
MyTestResourceGroup;MyTestResourceGroup2

If the value(s) already exists for an environment variable then you can also change the value by simply assigning the value to the variable. For example,

PS C:\Windows\system32> $env:AZURE_RESOURCE_GROUP = 'NewResourceGroup'
PS C:\Windows\system32> $env:AZURE_RESOURCE_GROUP
NewResourceGroup

The above method we have seen is to set the environment variable temporarily, once you close the PowerShell console the value gets destroyed. To add or set the environment variable persistently you need to use the .NET method.

Setting Environment Variable Persistently

To set the environment persistently so they should remain even when close the session, PowerShell uses [System.Environment] class with the SetEnvironmentVariable method for the environment variable to set it persistently.

[System.Environment]::SetEnvironmentVariable('ResourceGroup','AZ_Resource_Group')
PS C:\> $env:ResourceGroup
AZ_Resource_Group

Updated on: 29-Aug-2023

191K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements