Добавить переменную в path windows 10 через cmd

Для быстрого доступа к командам в командной строке без необходимости ввода полного пути к исполняемому файлу можно добавить путь к папке с этими исполняемыми файлами в переменную 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")

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!

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.

Do you know, how to set the patch from the command line? The Windows command prompt allows users to run executable files by supplying the absolute path to the file. Regardless of whether it’s just an executable file name. Depending on which environment variable is associated with the executable, Windows will search across a list of folders. The following variables are part of the environment.

Set Path from Command Line [Add to Path Windows]

A. System path &
B. User path

In the system properties, you can check the values of these variables (run the sysdm.cpl from computer properties or Run). User-specific paths are initially empty in the environment variable. This variable can be used to specify paths to directories containing executables. Administrators can also modify the environment variable indicating the path to the system.

Using the command line, how do you set a path?

Set paths from the command line in Windows 7 and Windows 10 by using the “setx” command.

setx path "%path%;c:\directoryPath"

The following command can be run to add c:/dir1/dir2 to the path variable.

setx path "%path%;c:\dir1\dir2"

It is also possible to use “pathman.exe” from the Windows resource kit. In addition to removing a directory from the path variable, we are also able to use the command described above. The same applies to Windows 7 as well.

Add directory to system path to set environment variable Windows cmd:

Step-1: Open the command prompt from the administrator.
Step-2: Then you need to run the following command below.

pathman /as directoryPath

Environment variable for system path should be removed:

From an elevated command prompt, execute the following command.

pathman /rs directoryPath

An environment variable to set the user path:

Users do not need admin privileges to access user environment variables. Add the following command to the environment variable user path to add a directory.

pathman /au directoryPath

Here is the command you can run to remove the directories from the user path.

pathman /ru directoryPath

As a default, ‘2’ times is the maximum amount of time you can allow each user:

Having no double quotes around ‘path’ results in this error. For an example of setting the Firefox path, see the following.

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.

When you move %path% inside double quotes it will look like this:

C:\Users\>setx path "%path%;c:\Program Files (x86)\Mozilla Firefox\"
SUCCESS: Specified value was saved.
C:\Users\>

Read: Stop Windows Update Service CMD

Download Windows Speedup Tool to fix errors and make PC run faster

Environment Variables are responsible for storing information about the OS’s environment. Different apps and programs require different configurations and it is the job of Windows to ensure that each of them has the environment best suitable for them. Simply speaking, these Environment Variables are data-storing facilities. A PATH variable is one of the most useful of the kind and helps you to run any executable found within Paths without having to give the full path to the executable. In this article, we will be discussing how you can manually add or edit existing PATH environment variables on Windows 11 or Windows 10.

An Environment variable is useful in the sense that it influences how software processes take place. The data stored in them play an important role in the process. Our tutorial will help you set up PATH variables so that you can run executables from your custom directories. These PATH variables store shortcuts, so you can create them for the programs of your choice. A prerequisite to push PATH variables through is to grant administrative privileges, so make sure you have them enabled. If you want a more detailed explanation of what System & User Environment Variables are, you can read the linked post.

How to set PATH variables manually on Windows 11/10

Without further ado, let’s see how you can add or edit a PATH Environment Variable in Windows 11/10:

  1. Click on the Search menu on the Taskbar and open the Windows Settings
  2. From the Settings panel, click on the System option from the left menu pane
  3. Go to About and further click on Advanced System Settings. This will open a dialog box named System Properties
  4. Here, click on the Advanced tab and further click on the Environment Variables button on the bottom-right
  5. This will open the Environment Variables panel. Here, variables will be divided into two categories: System and User Variables. The former is applicable for system-wide changes while the latter is used to make modifications to the environment of a particular user. Make a decision based on the purpose of creating or editing a PATH variable and select PATH from a section
  6. Follow this by clicking on the Edit button

add or edit a PATH Environment Variable in Windows

You can now modify the existing route lines with the ones you want your computer to access. This stuff may seem overwhelming to some of you and has very deep implications for some important PC processes, so you’re advised to express utmost caution.

In order to add a new route, you can click on the ‘New’ button. You can delete a Path the same way. Here, you can just paste the Path of your choice, and if you’re unsure of it, then you can use the Surf option to go about searching for it. Once you’re done, click on Ok and a new PATH variable will now exist.

Our guide here explains how you can add Environment Variables to your Windows Context Menu.

Read: How to see Names and Values of Environment Variables in Windows

How do I change Environment Variables without admin rights?

Granting administrative rights may not be as easy when the PC isn’t yours, but you can still make changes to your environment variables. Via the Control Panel, you can modify the environment variables on a user account, but not System variables. Here’s how you can do that:

  • Open the Control Panel
  • Select to view them as ‘Small icons’ and click on User Accounts
  • Here, you’ll see an option to your left named ‘Change my environment variables’
  • This will open the same Environment Variables dialog box as before, except now the System Variables aren’t accessible and you can only make changes to User variables

TIPS:

  • How to use Environment Variable Editor in PowerToys?
  • Rapid Environment Editor is a powerful free Environment Variables Editor for Windows.

How do I change the Path in Windows Command Prompt?

A command line on your Windows Terminal (Command Prompt) can help you add a Path to your Path environment variable. The changes that we have discussed above can be implemented via the Command Prompt as well, but again, are limited to the User’s environment only. Here’s how:

  • Search ‘CMD’ on the Taskbar search menu and select to run it as the administrator
  • Enter the command ‘Pathman /au’ and follow it by the Path to the directory you want to append.
  • Similarly, you can use a ‘Pathman/ru’ command to delete an existing Path to a directory

We hope that this post was helpful for you and that you can now take care of your Path environment variables with ease.

Shiwangi loves to dabble with and write about computers. Creating a System Restore Point first before installing new software, and being careful about any third-party offers while installing freeware is recommended.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 10 очень долго открывает папки
  • Вход в безопасный режим windows 10 через командную строку
  • Sony xperia windows phone
  • Installation log windows 10
  • Как сделать пуск черным в windows 10