Add path windows command prompt

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\>

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

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:

  1. Pressing Win + R to open the Run dialog.
  2. 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

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

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

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

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!

Для быстрого доступа к командам в командной строке без необходимости ввода полного пути к исполняемому файлу можно добавить путь к папке с этими исполняемыми файлами в переменную PATH в Windows, особенно это может быть полезным при работе с adb, pip и python, git, java и другими средствами разработки с отладки.

В этой пошаговой инструкции о том, как добавить нужный путь в системную переменную PATH в Windows 11, Windows 10 или другой версии системы: во всех актуальных версиях ОС действия будут одинаковыми, а сделать это можно как в графическом интерфейсе, так и в командной строке или PowerShell. Отдельная инструкция про переменные среды в целом: Переменные среды Windows 11 и Windows 10.

Добавление пути в PATH в Свойствах системы

Для возможности запуска команд простым обращением к исполняемому файлу без указания пути, чтобы это не вызывало ошибок вида «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом», необходимо добавить путь к этому файлу в переменную среды PATH.

Шаги будут следующими:

  1. Нажмите клавиши Win+R на клавиатуре (в Windows 11 и Windows 10 можно нажать правой кнопкой мыши по кнопке Пуск и выбрать пункт «Выполнить»), введите sysdm.cpl в окно «Выполнить» и нажмите Enter.
  2. Перейдите на вкладку «Дополнительно» и нажмите кнопку «Переменные среды».
    Открыть настройки переменных среды Windows

  3. Вы увидите список переменных среды пользователя (вверху) и системных переменных (внизу). PATH присутствует в обоих расположениях.
    Переменная среды PATH пользователя и системная

  4. Если вы хотите добавить свой путь в PATH только для текущего пользователя, выберите «Path» в верхней части и нажмите «Изменить» (или дважды нажмите по переменной PATH в списке). Если для всех пользователей — то же самое в нижней части.
  5. Для добавления нового пути нажмите «Создать», а затем впишите новый путь, который требуется добавить в переменную PATH в новой строке. Вместо нажатия «Создать» можно дважды кликнуть по новой строке для ввода нового пути.
    Добавление папки в переменную PATH

  6. После ввода всех необходимых путей нажмите «Ок» — ваша папка или папки добавлены в переменную PATH.

Внимание: после добавления пути в переменную PATH потребуется перезапустить командную строку (если она была запущена в момент изменения), чтобы использовать команды без указания полного пути.

Как добавить путь в переменную PATH в командной строке и PowerShell

Вы можете добавить переменную PATH для текущей сессии в консоли: то есть она будет работать до следующего запуска командной строки. Для этого используйте команду:

set PATH=%PATH%;C:\ваш\путь

Есть возможность добавить путь в PATH с помощью командной строки и на постоянной основе (внимание: есть отзывы, что может повредить записи в переменной PATH, а сами изменения производятся для системной переменной PATH), команда будет следующей:

setx /M path "%path%;C:\ваш\путь"
Добавление в PATH в командной строке

Набор команд для добавления пути в переменную PATH пользователя с помощью PowerShell:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$my_path = "C:\ваш\путь"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "User")

Если требуется добавить путь в системную переменную PATH для всех пользователей, последнюю команду изменяем на:

[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "Machine")

The Path environment variable feature in Windows is very important because it lets your computer know where to find the programs when you run them through Command Prompt. For example, if you add a folder path to the “Path” environment variable, you can run any program in that path by entering only its name (e.g. “name.exe”) instead of its whole address every time you want to run it.

This guide will show you how to add a folder to the Path environment variable in Windows 11 or 10. Doing this for a program you often run will save you a lot of hassle and time when executing commands that involve the program.

Add Folder to Path Environment Variable in Windows 11 10

What is the “Path” environment variable?

The Path environment variable is like a list inside your Windows operating system that helps your computer find and run programs directly from a command prompt or PowerShell without needing the full address of the program. It’s a bunch of folder addresses stuck together with semicolons (;). When you try to start a program, Windows looks through these folders in the order they’re listed to find the program’s executable file.

The big deal about the Path variable is it will truly save you a lot of time. Instead of typing the full path every time you want to run a program, you can just tell your computer to run it by typing only its name, and if the program’s folder is in the Path, Windows will know where to find it.

Related issue: Batch (.BAT) Files Not Running in Windows 11/10

Here’s what a Path environment variable look like:

C:\Windows\system32;C:\Windows;C:\Program Files\Java\jdk1.8.0_281\bin

In this example, there are three directories listed. If you run a command, Windows will check these directories in this order to find the program you’re trying to start. If it’s not in any of these, you’ll see an error message.

“[Program] is not recognized as an internal or external command” error

If you’re trying to run a program called “custom-command,” but its folder isn’t listed in the Path. When you try to start it, you might see an error saying:

'custom-command' is not recognized as an internal or external command, operable program or batch file.

is not recognized as an internal or external command Windows 11

This error means Windows can’t find the program in any of the Path directories. To fix this, you need to add the program’s folder to the Path, which we’ll talk about next, or simply type the full path to the program.

Useful tip: How to List Installed Programs in Windows 11

How to add a folder to the “Path” environment variable in Windows 11 or 10

Adding a folder to the Path can be done through a few methods – the system properties, CMD or PowerShell. Choose a method that you’re comfortable with.

Using System Properties

This method should be the easiest and most friendly for people who are not very into commands because it uses the graphical interface of the System Properties window to add or change the Path.

  1. Hit Windows + X and choose “System” from the menu that pops up.
  2. In the System window, click on “Advanced system settings” on the right.
    Windows 11 advanced system settings

  3. Go to the “Advanced” tab in the System Properties dialog and hit the “Environment Variables” button.
    View Environment Variables Windows 11

  4. Find the “Path” variable under “System variables,” select it, and press “Edit.” This opens the “Edit environment variable” window.
    Add Directory to Path Environment Variable Windows 11 10

  5. Here, you’ll see all the folders already in the Path. To add a new one, click “New” and type or paste its address. Tip: Use the “Copy as Path” option to get the folder path right, starting from the root (like C:\Users\YourUsername\custom-folder).
    Add Folder to Path Environment Variable in Windows 11 10

  6. Hit “OK” when you’re done. Your new folder is now part of the Path, and Windows will check it when looking for programs to run.

See also: Change File(s) Date & Timestamp via CMD or PowerShell

Using Command Prompt

In this method, you will use the Command Prompt to change the Path environment variable.

  1. Start a Command Prompt with admin rights by right-clicking on the Start button, choosing “Windows Terminal (Admin)”, and then picking “Command Prompt” from the list.
    Open Command Prompt from Windows Terminal

  2. Type this command, but use your own folder path instead of “YourFolderPath”:
    setx PATH "%PATH%;YourFolderPath"

    This adds your new folder path to the current Path variable. It’s important to keep the “%PATH%;” part to not lose the paths already there.
    To add the folder path in the system environment and prevents the system Path from being duplicated in the user Path, add the /M option like this:

    setx /M PATH "%PATH%;YourFolderPath"

    Add Folder to Path Environment Variable CMD

  3. Close the Command Prompt and open it again to see your changes. Your new folder should now be part of the Path environment variable.

Using PowerShell

This method involves PowerShell to update the Path environment variable.

  1. Open PowerShell with admin rights by right-clicking on the Start button and choosing “Windows Terminal (Admin)”.
  2. Type this command, swapping “YourFolderPath” with your folder path:
    [Environment]::SetEnvironmentVariable("Path",
    [Environment]::GetEnvironmentVariable("Path",
    [EnvironmentVariableTarget]::Machine) + ";YourFolderPath",
    [EnvironmentVariableTarget]::Machine)
    

    Add Folder to Path Environment Variable PowerShell

    This gets the current Path variable, adds your new folder path, and then updates the Path variable. The “;YourFolderPath” adds your new folder after the existing paths.

  3. Close PowerShell and open it again to check the changes. Your new folder should now be in the Path environment variable.

Note: If you need to write a multi-line command in PowerShell, press Shift + Enter to go to a new line without running the command. Press Enter to run it after you’ve typed all of it. This can be helpful for long commands or scripts.

Checking the changes

To make sure the folder is now in the Path environment variable, open a new Command Prompt window and type:

echo %PATH%

Look at the output and check if the folder path you added is there.

Check Path Environment Variable Windows 11 10

Some common issues

The below are some common problems you might encounter when adding a folder to the Path environment variable in Windows.

  • If CMD still gives you error after adding the path of a program you want to run, double-check for typos or mistakes in the folder path. It should be a full path without special characters.
  • Changes to the Path variable only affect new Command Prompt or PowerShell sessions. Restart them to see the changes.
  • If there’s still a problem, there might be a conflict with other software. Look through the Path variable for any outdated or duplicate paths and remove them.

Other common mistakes

It’s easy to make a small mistake that can cause big problems when you’re updating the Path variable.

  • Always back up the current state of the Path variable before making changes. This way, if something goes wrong, you can simply restore it to its original state.
  • Never delete the existing entries in the Path variable unless you are certain they are no longer needed. Removing important paths can stop other programs from running properly.

One last thing: Knowing Path variable priorities

The order of paths in the Path variable matters a lot because Windows checks them in sequence to find the executable files.

If two folders in the Path contain an executable with the same name, Windows will run the one in the folder that appears first in the Path order. You might want to place frequently accessed program directories higher up in the Path to speed up their launch times.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Темы для рабочего стола windows 10 как установить
  • Как сделать второй рабочий стол на windows 10 пустой
  • Как удалить internet start с компьютера windows 10
  • Как переустановить приложение фотографии windows 10
  • Как вернуть просмотр фотографий windows 10 через powershell