Table of Contents
What Are Environment Variables?
As the name suggests, environment variables store information about Windows and applications’ environments. And the PATH is an environment variable that specifies a set of directories, separated with semicolons (;), where executable programs or scripts are located. In this post we will show you How to Set the Path Environment Variables using Windows PowerShell?
Environment variable scopes
Before you are moving forward, you should know about the Scope. On Windows, environment variables can be defined in three scopes:
- Process (or session) scope: The Process scope contains the environment variables available in the current process, or PowerShell session. This list of variables is inherited from the parent process and is constructed from the variables in the Machine and User scopes. Closing the PowerShell window will revert the environment variables to its pre-determined state.
- User scope: User environment variables are specific only to the currently logged-in user.
- System (or Machine) scope: System environment variables are globally accessed by all users.
Set the Path Environment Variables using Windows PowerShell
For example, we have a simple PowerShell script located at D:\scripts\resetwsl.ps1 that reset then reinstall an WSL instance automatically.
wsl --unregister alpine
wsl --import alpine 'D:\wsl\import\alpine' 'D:\wsl\export\alpine.tar'
As you can see in the below output, to execute the reset script, we need to type the full path of the script or navigate to the script location.
#Output
PS C:\> D:\scripts\resetwsl.ps1
Unregistering.
The operation completed successfully.
Import in progress, this may take a few minutes.
The operation completed successfully.
PS C:\>
PS C:\> cd D:\scripts\
PS D:\scripts> .\resetwsl.ps1
Unregistering.
The operation completed successfully.
Import in progress, this may take a few minutes.
The operation completed successfully.
To simplify the process, after opening a new PowerShell window, we want to type the name of the script only to run it instead of typing the full path or navigating to the script location like this:
PS C:\> resetwsl.ps1
As you can see, PowerShell does not recognize the script because it only finds the scripts and executable files in the folders listed in the Path environment variables.
To achieve that goal, we need to add the home path (folder) of the scripts to the Path environment variables. In our case, we need to add D:\Scripts folder to the path environment variables.
Add a value to the Path environment variable (Process scope)
1. In PowerShell we can get the list of directories in the PATH environment variables using the below command:
$Env:PATH -split ";"
The output will show the values of the path environment variables. It is including the values in process, user and system scopes.
# Output
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\Users\mpnadmin\AppData\Local\Microsoft\WindowsApps
C:\Users\mpnadmin\AppData\Local\Programs\oh-my-posh\bin
C:\Users\mpnadmin\AppData\Local\Programs\Microsoft VS Code\bin
2. To add a new directory to the Path environment, you will need to append your new path to the path variables by performing a simple string operation.
$Env:PATH += ";D:\Scripts"
# Output
PS C:\> $Env:PATH += ";D:\Scripts"
PS C:\> $Env:PATH -split ";"
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\Users\mpnadmin\AppData\Local\Microsoft\WindowsApps
C:\Users\mpnadmin\AppData\Local\Programs\oh-my-posh\bin
C:\Users\mpnadmin\AppData\Local\Programs\Microsoft VS Code\bin
D:\Scripts
After running the command, we can run the script by enter its name (can use Tab for auto completion) instead of typing the full path of the script or navigating to its location.
Note: Using the $Env:PATH variable will only temporarily change the PATH environment variable in the current PowerShell session. Closing the PowerShell window will revert the PATH environment variable to its pre-determined state. To permanently change the value of our PATH environment variable, we can use the following method below.
Add a value to the Path environment variable (User scope)
1. The PATH environment variable is critical for other software as well, and inadvertently overwriting it can cause various problems. To begin, ensure you backup of your current PATH variable values by running the following command.
$Env:PATH >> 'C:\Env_Path.txt'
Get-Content 'C:\Env_Path.txt'
2. Now, to add a folder as a PATH value, use the below code snippet. For example, we will add the folder D:\scripts to the PATH environment variable. The code explanation:
- $dir: The directory that you want to add as a value in the Path environment variable.
- $regPath: The path of the Registry key stores environment variables.
- $currentStrings: The current strings of the path environment variable.
- $newStrings: Use the join operator to combine the current strings with the $dir.
- Remove-ItemProperty: Remove the Path value name of the HKCU:\Environment key.
- New-ItemProperty: Recreate the value name with the new string ($newStrings)
# Don't forget to change the directory to fit with yours
$dir = "D:\Scripts"
$regPath = "HKCU:\Environment"
$currentStrings = (Get-ItemProperty $regPath ).Path
$newStrings = -join($currentStrings,$dir,";")
Remove-ItemProperty -Path $regPath -Name "Path" -Force
New-ItemProperty -Path $regPath -PropertyType 'ExpandString' -Name 'Path' -Value "$newStrings"
As you can see, the D:\Scripts has been added as a value of the Path environment variable.
# Output - The Path value is truncated
Path : C:\Users\mpnadmin\AppData\Local\Microsoft\WindowsApps;...;D:\Scripts;
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Environment
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER
PSChildName : Environment
PSDrive : HKCU
PSProvider : Microsoft.PowerShell.Core\Registry
How to we know it works? Close the opening PowerShell windows then open a new one then check the path env again using the $env:PATH -split ‘;’ command.
PS C:\> $env:PATH -split ';'
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\Users\mpnadmin\AppData\Local\Microsoft\WindowsApps
C:\Users\mpnadmin\AppData\Local\Programs\oh-my-posh\bin
C:\Users\mpnadmin\AppData\Local\Programs\Microsoft VS Code\bin
D:\Scripts
In the feature, the script should be executed by enter its name (can use Tab for auto completion) instead of typing the full path of the script or navigating to its location.
Add a value to the Path environment variable (System scope)
Note: The previous code snippet will add the folder to the PATH environment variable in user scope. If you want to do it in system scope (all users). You can use the following code snippet:
# Don't forget to change the directory to fit with yours
$dir = "D:\Scripts"
$regPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
$currentStrings = (Get-ItemProperty -Path $regPath).Path
$newStrings = -join($currentStrings,$dir,";")
Remove-ItemProperty -Path $regPath -Name "Path" -Force
New-ItemProperty -Path $regPath -PropertyType 'ExpandString' -Name 'Path' -Value "$newStrings"
Set environment variables in your profile
Alternatively, a PowerShell profile is a script that runs when PowerShell starts. You can use the profile as a startup script to customize your environment. You can add commands, aliases, functions, variables, modules, PowerShell drives and more. They’re available in every session without having to import or re-create them.
If you’re writing the PowerShell script to run locally on your computer. You can use the PowerShell profile to add a directory to the path environment variables. Every time you start a PowerShell session the variables would be added automatically.
PowerShell supports several profiles for users and host programs. However, it doesn’t create the profiles for you. Let’s run the below command to create a profile for you if it does not exist.
if(!(Test-Path $profile)){New-Item -Type File -Path $profile -Force}
On the PowerShell profile is created, open it using Notepad then add $Env:PATH += ‘;D:\Scripts’. Close Notepad and save the file.
notepad.exe $PROFILE
From now, every time when open a PowerShell session:
- The PowerShell profile is loaded.
- The command $Env:PATH += ‘;D:\Scripts’ is executed automatically.
- And then the folder D:\Scripts would be added as a path environment variable for the session.
Additionally, the command could be added to the PowerShell profile usinh the below command:
Add-Content $PROFILE -Value "`$Env:PATH += ';D:\Scripts'"
Using the Add-Content cmdlet, you can append more paths to the PowerShell profile ($profile) automatically when running your script.
PS C:\> Add-Content $PROFILE -Value "`$Env:PATH += ';D:\Scripts'"
PS C:\> Add-Content $PROFILE -Value "`$Env:PATH += ';C:\Scripts'"
PS C:\> Get-Content $PROFILE
$Env:PATH += ';D:\Scripts'
$Env:PATH += ';C:\Scripts'
To verify it works, open a new PowerShell session then check if D:\Scripts is added automatically.
Because it’s automatically added every time you start PowerShell. So, we can consider it is persistent.
PowerShell execution policy
In the first time after creating the PowerShell profile, when starting PowerShell, you could get the below error:
. : File C:\Users\WDAGUtilityAccount\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 cannot be loaded
because running scripts is disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ . 'C:\Users\WDAGUtilityAccount\Documents\WindowsPowerShell\Microsoft. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
You get it because by default, Windows does not allow to run any PowerShell script. PowerShell profile is a PowerShell script, so, it is blocked from running.
PS C:\> $PROFILE
C:\Users\admin\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
To fix it, let’s run the below command in an elevated PowerShell session. Close then re-open PowerShell to see it works without any error.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
Why it seems complicated?
When using the PowerShell code snippet (registry method) to add a folder as a value of the Path environment variables. You may wonder Why it looks complicated?
As we show you in the first part of this post, most of the articles on the internet guide you to use the below simple command to add a directory to the Path environment variables. For example, add D:\Scripts to the env:
$Env:PATH += ";D:\Scripts"
You can see, it works as expected but it’s not persistent. Closing the PowerShell window and then re-open a new one will revert the environment variables to its pre-determined state because it’s process scope.
PS C:\> $Env:PATH += ";D:\Scripts"
PS C:\> $env:PATH -split ";"
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\Users\admin\AppData\Local\Microsoft\WindowsApps
C:\Users\admin\AppData\Local\Programs\oh-my-posh\bin
C:\Users\admin\AppData\Local\Programs\Microsoft VS Code\bin
D:\Scripts
Some other guides on the internet tell you using the below command to persistent add a value to path environment variables in PowerShell:
setx PATH "$Env:PATH;D:\scripts"
PS C:\> setx PATH "$Env:PATH;D:\scripts"
SUCCESS: Specified value was saved.
Seem it works right?
The answer is YES BUT NOT RECOMMENED, when you get the values of the path environment variables. You will see, setx duplicates values from a scope to another one.
PS C:\> $Env:PATH -split ";"
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\Users\admin\AppData\Local\Microsoft\WindowsApps
C:\Users\admin\AppData\Local\Programs\oh-my-posh\bin
C:\Users\admin\AppData\Local\Programs\Microsoft VS Code\bin
D:\Scripts
D:\scripts
Not a reader? Watch this related video tutorial: