I just stumbled upon a necessity to add a directory to my Windows PATH variable. I usually do this using the GUI method which is quite easy.
But I thought it would be great and faster if I’m able to add it directly from my already open PowerShell.
Without further ado, here is how to add new directory to PATH variable using PowerShell:
Warning: the steps below involves modifying Windows registry. Your OS might be damaged if you change the registry incorrectly. Please be careful when following the tutorial.
- Open PowerShell with administrator rights. Right-click the PowerShell shortcut/icon and click Run as administrator. You can also do this via Windows Terminal.
- Check the directory you want to add first and make sure it doesn’t exist in your PATH yet:
- Run this command to get the old PATH:
$oldpath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path
- Add the new PATH:
$newpath = "$oldpath;C:\new\path"
Notice the “;” between the old path and the new path. It’s necessary to add it to prevent the new path interfering the old path.
- Apply the new path and set in the PATH variable:
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newpath
- Close and reopen your PowerShell.
- Check the new PATH and make sure the new entry has been added:
That’s it! Although arguably adding a new entry to the PATH variable would be easier using GUI, adding it via PowerShell is also quite straightforward.