PATH
is an environment variable that specifies a set of directories, separated with semicolons (;
), where executable programs are located.
In this note i am showing how to print the contents of Windows PATH
environment variable from the Windows command prompt.
I am also showing how to add a directory to Windows PATH
permanently or for the current session only.
Cool Tip: List environment variables in Windows! Read More →
Print the contents of the Windows PATH
variable from cmd
:
C:\> path
– or –
C:\> echo %PATH%
The above commands return all directories in Windows PATH
environment variable on a single line separated with semicolons (;
) that is not very readable.
To print each entry of Windows PATH
variable on a new line, execute:
C:\> echo %PATH:;=&echo.%
- sample output -
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
C:\WINDOWS\System32\WindowsPowerShell\v1.0\
C:\WINDOWS\System32\OpenSSH\
C:\Program Files\Intel\WiFi\bin\
C:\Program Files\Common Files\Intel\WirelessCommon\
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL
C:\Program Files\Intel\Intel(R) Management Engine Components\DAL
C:\Program Files\Microsoft VS Code\bin
C:\Users\Admin\AppData\Local\Microsoft\WindowsApps
Cool Tip: Set environment variables in Windows! Read More →
Add To Windows PATH
Warning! This solution may be destructive as Windows truncates PATH
to 1024 characters. Make a backup of PATH
before any modifications.
Save the contents of the Windows PATH
environment variable to C:\path-backup.txt
file:
C:\> echo %PATH% > C:\path-backup.txt
Set Windows PATH For The Current Session
Set Windows PATH
variable for the current session:
C:\> set PATH="%PATH%;C:\path\to\directory\"
Set Windows PATH Permanently
Run as Administrator: The setx
command is only available starting from Windows 7 and requires elevated command prompt.
Permanently add a directory to the user PATH
variable:
C:\> setx path "%PATH%;C:\path\to\directory\"
Permanently add a directory to the system PATH
variable (for all users):
C:\> setx /M path "%PATH%;C:\path\to\directory\"
Info: To see the changes after running setx
– open a new command prompt.
Was it useful? Share this post with the world!
Users can run an executable from windows command prompt either by giving the absolute path of the file or just by the executable file name. In the latter case, Windows searches for the executable in a list of folders which is configured in environment variables. These environment variables are as below.
1. System path
2. User path
The values of these variables can be checked in system properties( Run sysdm.cpl from Run or computer properties). Initially user specific path environment variable will be empty. Users can add paths of the directories having executables to this variable. Administrators can modify the system path environment variable also.
How to set path from command line?
In Vista, Windows 7 and Windows 8 we can set path from command line using ‘setx’ command.
setx path "%path%;c:\directoryPath"
For example, to add c:\dir1\dir2 to the path variable, we can run the below command.
setx path "%path%;c:\dir1\dir2"
Alternative way is to use Windows resource kit tools ‘pathman.exe‘. Using this command we can even remove a directory from path variable. See download windows resource kit tools. This works for Windows 7 also.
Add directory to system path environment variable:
Open administrator command prompt
Run the below command
pathman /as directoryPath
Remove path from system path environment variable:
Run the below command from elevated command prompt
pathman /rs directoryPath
Setting user path environment variable
For user environment varlables, admin privileges are not required. We can run the below command to add a directory to user path environment variable.
pathman /au directoryPath
To remove a directory from user path, you can run the below command.
pathman /ru directoryPath
Default option is not allowed more than ‘2’ time(s)
You get this error if you have not enclosed ‘path’ in double quotes. See the below example for setting the path of firefox.
C:\Users\>setx path %path%;"c:\Program Files (x86)\Mozilla Firefox\" ERROR: Invalid syntax. Default option is not allowed more than '2' time(s). Type "SETX /?" for usage.
Now if you move %path% to be in the double quotes
C:\Users\>setx path "%path%;c:\Program Files (x86)\Mozilla Firefox\" SUCCESS: Specified value was saved. C:\Users\>
Sometimes we need to tell Windows where to look for a particular executable file or script. Windows provides a means to do this through the Path Environment Variable. The Path Environment Variable essentially provides the OS with a list of directories to look in for a particular .exe or file when the simple name of the file is entered at the command prompt.
For example, the Notepad.exe application resides in the C:\Windows\system32 directory. However, if we wish to open the Notepad application via the Windows Command Line, we need only type:
Opening Notepad.exe From the Windows Command Line:
C:\Users\John> notepad
This works because the Path variable on Windows by default contains a list of directories where application files and scripts are likely to be located. Each directory in the list is separated by a semi-colon.
Similarly, there is another environment variable, PATHEXT which specifies a list of file extensions which might be found when searching for the proper file within the paths in the Path variable. This is why we are able to type simply “Notepad” at the command prompt, instead of Notepad.exe.
Windows will first search the current directory (where the command prompt is a the time the command is executed) to find a name matching the one typed into the terminal, and then search the directories in the Path variable in order, beginning with the most likely locations, and continue until either a matching file name is located, or else return the “… is not recognized blah blah” message at the terminal.
Once a file with a matching name is located, Windows attempts to match the file extension (if one is present), again in the order specified in the PATHEXT variable. If a match is found, the file is processed accordingly.
There are both User-specific and machine-level PATH variables. Machine Path variables are available globally across the machine, and can only be modified by administrators. User Environment variables can be modified by both administrators, and the user with which the current profile is associated.
Adding a Directory to the User Path Variable from the Command Line
Any user can modify their own PATH variable from the Command Line (unless they have been specifically denied this ability by an administrator).
For example, when we wish to use SQLite from the Windows Command Line, we download the SQLite binaries, and place them in the directory of choice. However, in order to use the SQLite Command Line application without either navigating directly to the folder in which we placed it, or entering the full file path into our Windows Command Line, we need to add the directory containing the SQLite.exe to our User or System PATH environment variable.
Let’s say a user has downloaded the sqlite3.dll and sqlite3.exe binaries and located them in the directory C:\SQLite.
Now, in order to invoke the sqlite3.exe from the command line, we need to add the C:\SQLite directory to our PATH environment variable. We can do this from the command line by using the setx command:
The setx Command – Syntax:
C:\Users\John> setx "%path%;C:\SQLite"
When we modify environment variables using setx, the changes are not available in the current Console session – in other words, in order to see our changes, we need to exit, and open a new Console window. Then, we can use the following technique:
We can examine the contents of the PATH variable by typing:
Output PATH Variable to the Console:
C:\Users\John> echo %PATH%
Which gives the output:
Results of Echo %PATH% Command:
C:\Users\John>echo %PATH% C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind owsPowerShell\v1.0\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\ Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\1 10\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\Manage mentStudio\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Priv ateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Prog ram Files (x86)\Common Files\Acronis\SnapAPI\;C:\Program Files (x86)\Windows Liv e\Shared;C:\Program Files\Calibre2\;C:\Program Files\Microsoft\Web Platform Inst aller\;C:\Users\John\AppData\Roaming\npm;C:\Program Files (x86)\nodejs\;C:\Progr am Files (x86)\Microsoft SDKs\Windows Azure\CLI\wbin;C:\Program Files (x86)\GtkS harp\2.12\bin;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\SQLite
We can see here that C:\SQLite has now been added to the paths available to the current user.
Adding a Directory to the System Path Variable from the Command Line
In the previous section, we used the setx command to add a directory to the current user’s Path variable. Sometimes, we want to make variables available at the system, or machine level. In that case, we use the same setx
command in conjunction with the /m flag. However, we need to run the Command Terminal as Administrator for this to work:
Add a Directory the the System PATH Variable Using the /m Flag:
C:\Users\John> setx /m path "%path%;C:\SQLite"
Adding a Directory to the Path Variable from the GUI
Or, we can do this using the GUI by navigating to Control Panel => All Control Panel Items => System, and then selecting the “Advanced System Settings” link:
Locate Advanced System Settings in Control Panels:
Then locate the “Environment Variables” button:
Open Environment Variables:
Opening Environment Variables, we see the following:
Editing Environment Variables:
Notice in the image above, there are two sections, User Variables for<Current User>, and System Variables.
Also note, there is not currently a Path variable for me, the current user. We will need to add one, and then add our new path to it:
Adding a User Path Variable in the Windows GUI:
Once we hit OK, We see we have the single item added to our user path variable.
Added Path Variable to User Environment Variables:
For some reason, this works differently than when we do this from the Command Line, when we use the setx
command from the terminal, the entirety of the system path variable is copied into the user path variable, including the new entry.
If we have Administrator permissions on our machine, we can do the same for the System PATH variable if we so choose.
Removing Directories from the PATH Variable
In some cases, we may need to remove a directory from our PATH variable. In these cases it is recommended to use the GUI, or edit the registry. It’s easiest to simply open the GUI, copy the contents of the PATH variable (either the User Path or the System Path) to a text editor, and remove the entries you want to delete. Then paste the remaining text back into the Edit Path window, and save.
Additional Resources and Items of Interest
- Installing and Using SQLite on Windows
- Getting Started with Git for the Windows Developer (Part I)
- Basic Git Command Line Reference for Windows Users
- Git: Interactively Stage Portions of a Single Changed File for Commit Using git add -p
Для быстрого доступа к командам в командной строке без необходимости ввода полного пути к исполняемому файлу можно добавить путь к папке с этими исполняемыми файлами в переменную PATH в Windows, особенно это может быть полезным при работе с adb, pip и python, git, java и другими средствами разработки с отладки.
В этой пошаговой инструкции о том, как добавить нужный путь в системную переменную PATH в Windows 11, Windows 10 или другой версии системы: во всех актуальных версиях ОС действия будут одинаковыми, а сделать это можно как в графическом интерфейсе, так и в командной строке или PowerShell. Отдельная инструкция про переменные среды в целом: Переменные среды Windows 11 и Windows 10.
Добавление пути в PATH в Свойствах системы
Для возможности запуска команд простым обращением к исполняемому файлу без указания пути, чтобы это не вызывало ошибок вида «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом», необходимо добавить путь к этому файлу в переменную среды PATH.
Шаги будут следующими:
- Нажмите клавиши Win+R на клавиатуре (в Windows 11 и Windows 10 можно нажать правой кнопкой мыши по кнопке Пуск и выбрать пункт «Выполнить»), введите sysdm.cpl в окно «Выполнить» и нажмите Enter.
- Перейдите на вкладку «Дополнительно» и нажмите кнопку «Переменные среды».
- Вы увидите список переменных среды пользователя (вверху) и системных переменных (внизу). PATH присутствует в обоих расположениях.
- Если вы хотите добавить свой путь в PATH только для текущего пользователя, выберите «Path» в верхней части и нажмите «Изменить» (или дважды нажмите по переменной PATH в списке). Если для всех пользователей — то же самое в нижней части.
- Для добавления нового пути нажмите «Создать», а затем впишите новый путь, который требуется добавить в переменную PATH в новой строке. Вместо нажатия «Создать» можно дважды кликнуть по новой строке для ввода нового пути.
- После ввода всех необходимых путей нажмите «Ок» — ваша папка или папки добавлены в переменную PATH.
Внимание: после добавления пути в переменную PATH потребуется перезапустить командную строку (если она была запущена в момент изменения), чтобы использовать команды без указания полного пути.
Как добавить путь в переменную PATH в командной строке и PowerShell
Вы можете добавить переменную PATH для текущей сессии в консоли: то есть она будет работать до следующего запуска командной строки. Для этого используйте команду:
set PATH=%PATH%;C:\ваш\путь
Есть возможность добавить путь в PATH с помощью командной строки и на постоянной основе (внимание: есть отзывы, что может повредить записи в переменной PATH, а сами изменения производятся для системной переменной PATH), команда будет следующей:
setx /M path "%path%;C:\ваш\путь"
Набор команд для добавления пути в переменную PATH пользователя с помощью PowerShell:
$PATH = [Environment]::GetEnvironmentVariable("PATH") $my_path = "C:\ваш\путь" [Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "User")
Если требуется добавить путь в системную переменную PATH для всех пользователей, последнюю команду изменяем на:
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "Machine")
To add a directory to the system PATH environment variable using the command prompt, you can use the following command:
setx PATH "%PATH%;C:\path\to\your\directory"
Understanding the PATH Variable
What is the PATH Variable?
The PATH variable is an environment variable that specifies a set of directories where executable programs are located. When you type a command into the command prompt, Windows searches these directories for the executable file associated with that command. If the file isn’t found in any of the directories listed in the PATH, you’ll get an error indicating that the command is not recognized. Understanding how to manage this variable is crucial for efficient command-line operation.
How PATH Works in Windows
On Windows, the PATH variable contains multiple directories, each separated by a semicolon. You can have two types of PATHs:
- User-specific PATH: This applies only to the currently logged-in user.
- System-wide PATH: This affects all users on the system.
When you add a directory to the PATH, you are essentially telling the command prompt «look here for executable files.»
How to SSH from Cmd: A Quick Guide to Secure Connections
Setting PATH in Windows CMD
Accessing Command Prompt
To modify the PATH variable using the command prompt, you first need to access CMD. You can do this by:
- Pressing Win + R to open the Run dialog.
- Typing `cmd` and pressing Enter.
Viewing the Current PATH
Before making changes, it’s important to know the current state of your PATH. To view your existing PATH variable, you can simply run:
echo %PATH%
This command will display a long list of directories currently in your PATH, making it easier to identify where you might want to add new directories.
How to Set PATH in Windows CMD
Temporary PATH Changes
If you need a quick change for the current command prompt session, you can add a directory temporarily. This change will last until you close the command prompt. You can do this using the `set` command:
set PATH=%PATH%;C:\Your\Directory\Here
Important: Replace `C:\Your\Directory\Here` with the actual directory you wish to add. This command appends your chosen directory to the existing PATH for the session only.
Permanent PATH Changes
If you want the changes to persist across sessions, you need to set the PATH variable permanently using the `setx` command.
To add a directory permanently, use the following command:
setx PATH "%PATH%;C:\Your\Permanent\Directory\Here"
Here, remember that the `setx` command does not affect the current command prompt session. You will need to open a new command prompt to see the updated PATH.
Mastering Getpaths.cmd: A Quick Guide to File Paths
Common Issues and Troubleshooting
PATH Length Limitations
Windows has a maximum PATH length of 2048 characters. Exceeding this limit can lead to unpredictable results. To manage your PATH efficiently:
- Regularly review directories included in your PATH.
- Remove any that are no longer necessary or are duplicates.
Verifying the Changes
After making changes to the PATH variable, it’s essential to verify that everything has been updated correctly. You can re-run the command to display the current PATH:
echo %PATH%
If you do not see your newly added directory, ensure that you’ve closed and reopened the command prompt.
How to Exit from Cmd: A Quick and Easy Guide
Practical Examples
Adding a Python Installation to PATH
Python is a powerful tool for scripting, and adding it to your PATH allows you to run Python scripts easily from any directory. If you have Python installed in `C:\Python39`, you can add it to your PATH by executing:
setx PATH "%PATH%;C:\Python39"
Note: Be sure to close and reopen CMD to use Python commands immediately after.
Adding Git to PATH
If you use Git for version control, adding its installation path makes it more efficient to run Git commands. If Git is installed under `C:\Program Files\Git\bin`, you can add it like so:
setx PATH "%PATH%;C:\Program Files\Git\bin"
By adding Git to your PATH, you can easily use commands like `git clone`, `git commit`, and `git push` from any command line interface without navigating to its directory.
How to Boot from Cmd: A Quick User Guide
Conclusion
Adding to the PATH from CMD is a straightforward yet powerful process. Whether you’re looking to enhance your productivity or simply make your command line experience smoother, managing the PATH variable effectively will save you time and effort. Don’t hesitate to experiment with different commands and paths in CMD, as mastering this tool can significantly improve your workflow.
Reset PC from Cmd: A Simple Guide to Get Started
Additional Resources
To delve deeper into the world of command line operations and environment variables, refer to related articles and guides that expand upon these foundational concepts. This journey into CMD can open countless possibilities for automation and productivity!