Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

How to Add a Path to the Windows PATH Environment Variables

July 23, 2024
in A, Blog, Powershell
0
ADVERTISEMENT

Table of Contents

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 add a directory to Windows PATH.

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.
PZYOB7XxNDHkveS0DMtGuHwSdFdwfcLJigCrBJY3stuL5qLlJTar4YDzJBZv

Set Environment Variable in Windows Using 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.

xEu93WPkiiSu8RlcU9k1HtLLnV2e7o7jbZzW10p1CjLt2GK3KzPnubVrdbNH

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 (User scope)

1. In PowerShell we can get the list of directories in the PATH environment variable using the below command:

$Env:PATH -split ";"

The output will show the value of the path environment variables. It is including the values in both 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. 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'
HiNfcXuyHI64AOaI7NncKU51GHj0dtjwmY7xcuxmNtIqcU0DCnX9bBzv6F0y

3. 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

To verify it works, close the opening PowerShell windows then open a new one then check the path env again.

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

From now, after opening the PowerShell, 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.

8QxUjsohFwGuY2vBMGqbeg2DfjWlj9px3s7vl5WBIOlekccJBzQLpaNKrBvp

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"

Why it seems complicated?

When using the PowerShell code snippet to add a folder as a value of the Path environment variables. You may wonder Why it looks complicated?

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"

As 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
So, DO NOT USE setx command to add a Path in the environment variables.

Set environment variables in your profile

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:

  1. The PowerShell profile is loaded.
  2. The command $Env:PATH += ‘;D:\Scripts’ is executed automatically.
  3. And then the folder D:\Scripts would be added as a path environment variable for the session.
Fb6Gw2SzrGfid1CVcPQFb2WNQPqQdWKPZ5Eiw6OXYdKHMF23rGd7AgX4lpvk

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.

caUUF7Mk3GJCF4sdEbv8jGMWPj5EGlYKk2EYucImFrO5nABPmlJOKktJRNl1

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

Related: How to Configure the PowerShell Execution Policy on Windows

Add a Directory to PATH Environment Variables in GUI

Alternatively, if you don’t want to do it using PowerShell. You can do it with GUI from Control Panel.

1. Type env into the search box, under the best match select Edit the system environment variables.

PZYOB7XxNDHkveS0DMtGuHwSdFdwfcLJigCrBJY3stuL5qLlJTar4YDzJBZv

2. In the System Properties window, select Environment Variables…

BAZLK9KR08D9TB2MWe1pmExh0DbTQiKR08DojchqGO2kNE8I10HTrRRMBDIp

3. You can add the folder to either user or system variables. For instance, we will add it to the PATH environment variable in the user scope. Select Path → Edit…

2P20lMkRALcY877wfPJ8ifaL1vdHJjNhyY0IFig3ZjUesYXNfxDxycyrpW0p

4. Click New → Enter the path of the folder you want to add to. In our case, we add D:\Scripts.

ONwnCvKWNaMwhLl47vzYnVJb8ZzZPBXvgmcomjgbCgLkqNrS01ucCOYr9Xfu

5. Click OK three times to save the changes.

Finally, open a new PowerShell window, from now, 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.

8QxUjsohFwGuY2vBMGqbeg2DfjWlj9px3s7vl5WBIOlekccJBzQLpaNKrBvp
ADVERTISEMENT

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

How to Wipe a WSL Distro in Windows Subsystem for Linux

Next Post

How to Add a Directory to Windows %PATH% Environment Variables

Related Posts

Images Hidden Due To Mature Content Settings In CivitAI

August 31, 2024

Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

August 20, 2024

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024

How to Remove The Test Mode Watermark Without Disabling Test Mode

July 28, 2024

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory