Windows как добавить в path через консоль

Add a directory to Windows PATH environment variable from CMD. Set Windows PATH permnently or for the current session. Echo (print) Windows PATH variable.

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

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:pathtodirectory"

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:pathtodirectory"

Permanently add a directory to the system PATH variable (for all users):

C:> setx /M path "%PATH%;C:pathtodirectory"

Info: To see the changes after running setx – open a new command prompt.

I am trying to add C:xamppphp to my system PATH environment variable in Windows.

I have already added it using the Environment Variables dialog box.

But when I type into my console:

C:>path

it doesn’t show the new C:xamppphp directory:

PATH=D:Program FilesAutodeskMaya2008bin;C:Ruby192bin;C:WINDOWSsystem32;C:WINDOWS;
C:WINDOWSSystem32Wbem;C:PROGRA~1DISKEE~2DISKEE~1;c:Program FilesMicrosoft SQL
Server90Toolsbinn;C:Program FilesQuickTimeQTSystem;D:Program FilesTortoiseSVNbin
;D:Program FilesBazaar;C:Program FilesAndroidandroid-sdktools;D:Program Files
Microsoft Visual StudioCommonToolsWinNT;D:Program FilesMicrosoft Visual StudioCommon
MSDev98Bin;D:Program FilesMicrosoft Visual StudioCommonTools;D:Program Files
Microsoft Visual StudioVC98bin

I have two questions:

  1. Why did this happen? Is there something I did wrong?
  2. Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?

Peter Mortensen's user avatar

asked Mar 3, 2012 at 12:58

Netorica's user avatar

8

Option 1

After you change PATH with the GUI, close and reopen the console window.

This works because only programs started after the change will see the new PATH.

Option 2

This option only affects your current shell session, not the whole system. Execute this command in the command window you have open:

set PATH=%PATH%;C:yourpathhere

This command appends C:yourpathhere to the current PATH. If your path includes spaces, you do not need to include quote marks.

Breaking it down:

  • set – A command that changes cmd’s environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:yourpathhere – The %PATH% part expands to the current value of PATH, and ;C:yourpathhere is then concatenated to it. This becomes the new PATH.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:03

JimR's user avatar

JimRJimR

15.1k2 gold badges20 silver badges26 bronze badges

12

WARNING: This solution may be destructive to your PATH, and the stability of your system. As a side effect, it will merge your user and system PATH, and truncate PATH to 1024 characters. The effect of this command is irreversible. Make a backup of PATH first. See the comments for more information.

Don’t blindly copy-and-paste this. Use with caution.

You can permanently add a path to PATH with the setx command:

setx /M path "%path%;C:yourpathhere"

Remove the /M flag if you want to set the user PATH instead of the system PATH.

Notes:

  • The setx command is only available in Windows 7 and later.
  • You should run this command from an elevated command prompt.

  • If you only want to change it for the current session, use set.

StayOnTarget's user avatar

StayOnTarget

10.9k10 gold badges49 silver badges75 bronze badges

answered Feb 28, 2015 at 5:12

Nafscript's user avatar

NafscriptNafscript

4,9572 gold badges16 silver badges15 bronze badges

15

This only modifies the registry. An existing process won’t use these values. A new process will do so if it is started after this change and doesn’t inherit the old environment from its parent.

You didn’t specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:23

Hans Passant's user avatar

Hans PassantHans Passant

913k145 gold badges1670 silver badges2507 bronze badges

6

You don’t need any set or setx command. Simply open the terminal and type:

PATH

This shows the current value of PATH variable. Now you want to add directory to it? Simply type:

PATH %PATH%;C:xamppphp

If for any reason you want to clear the PATH variable (no paths at all or delete all paths in it), type:

PATH ;

Update

Like Danial Wilson noted in comment below, it sets the path only in the current session. To set the path permanently, use setx but be aware, although that sets the path permanently, but not in the current session, so you have to start a new command line to see the changes. More information is here.

To check if an environmental variable exist or see its value, use the ECHO command:

echo %YOUR_ENV_VARIABLE%

Peter Mortensen's user avatar

answered Jul 1, 2015 at 15:11

zar's user avatar

zarzar

10.9k13 gold badges90 silver badges171 bronze badges

6

I would use PowerShell instead!

To add a directory to PATH using PowerShell, do the following:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$xampp_path = "C:xamppphp"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path")

To set the variable for all users, machine-wide, the last line should be like:

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

In a PowerShell script, you might want to check for the presence of your C:xamppphp before adding to PATH (in case it has been previously added). You can wrap it in an if conditional.

So putting it all together:

$PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
$xampp_path = "C:xamppphp"
if( $PATH -notlike "*"+$xampp_path+"*" ){
    [Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path", "Machine")
}

Better still, one could create a generic function. Just supply the directory you wish to add:

function AddTo-Path{
param(
    [string]$Dir
)

    if( !(Test-Path $Dir) ){
        Write-warning "Supplied directory was not found!"
        return
    }
    $PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
    if( $PATH -notlike "*"+$Dir+"*" ){
        [Environment]::SetEnvironmentVariable("PATH", "$PATH;$Dir", "Machine")
    }
}

You could make things better by doing some polishing. For example, using Test-Path to confirm that your directory actually exists.

Mariano Desanze's user avatar

answered Mar 17, 2015 at 20:24

Ifedi Okonkwo's user avatar

Ifedi OkonkwoIfedi Okonkwo

3,3064 gold badges31 silver badges45 bronze badges

4

Safer SETX

Nod to all the comments on the @Nafscript’s initial SETX answer.

  • SETX by default will update your user path.
  • SETX ... /M will update your system path.
  • %PATH% contains the system path with the user path appended

Warnings

  1. Backup your PATHSETX will truncate your junk longer than 1024 characters
  2. Don’t call SETX %PATH%;xxx — adds the system path into the user path
  3. Don’t call SETX %PATH%;xxx /M — adds the user path into the system path
  4. Excessive batch file use can cause blindness1

The ss64 SETX page has some very good examples. Importantly it points to where the registry keys are for SETX vs SETX /M

User Variables:

HKCUEnvironment

System Variables:

HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment

Usage instructions

Append to User PATH

append_user_path.cmd

@ECHO OFF
REM usage: append_user_path "path"
SET Key="HKCUEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > user_path_bak.txt
SETX PATH "%CurrPath%";%1

Append to System PATH

append_system_path.cmd. Must be run as administrator.

(It’s basically the same except with a different Key and the SETX /M modifier.)

@ECHO OFF
REM usage: append_system_path "path"
SET Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > system_path_bak.txt
SETX PATH "%CurrPath%";%1 /M

Alternatives

Finally there’s potentially an improved version called SETENV recommended by the ss64 SETX page that splits out setting the user or system environment variables.


Example

Here’s a full example that works on Windows 7 to set the PATH environment variable system wide. The example detects if the software has already been added to the PATH before attempting to change the value. There are a number of minor technical differences from the examples given above:

@echo off
set OWNPATH=%~dp0
set PLATFORM=mswin

if defined ProgramFiles(x86)                        set PLATFORM=win64
if "%PROCESSOR_ARCHITECTURE%"=="AMD64"              set PLATFORM=win64
if exist "%OWNPATH%textexmf-mswinbincontext.exe" set PLATFORM=mswin
if exist "%OWNPATH%textexmf-win64bincontext.exe" set PLATFORM=win64

rem Check if the PATH was updated previously
echo %PATH% | findstr "texmf-%PLATFORM%" > nul

rem Only update the PATH if not previously updated
if ERRORLEVEL 1 (
  set Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
  for /F "USEBACKQ tokens=2*" %%A in (`reg query %%Key%% /v PATH`) do (
    if not "%%~B" == "" (
      rem Preserve the existing PATH
      echo %%B > currpath.txt

      rem Update the current session
      set PATH=%PATH%;%OWNPATH%textexmf-%PLATFORM%bin
      
      rem Persist the PATH environment variable
      setx PATH "%%B;%OWNPATH%textexmf-%PLATFORM%bin" /M
    )
  )
)

1. Not strictly true

Dave Jarvis's user avatar

Dave Jarvis

29.9k39 gold badges177 silver badges310 bronze badges

answered Dec 29, 2016 at 12:04

icc97's user avatar

icc97icc97

10.6k8 gold badges68 silver badges88 bronze badges

0

Handy if you are already in the directory you want to add to PATH:

set PATH=%PATH%;%CD%

It works with the standard Windows cmd, but not in PowerShell.

For PowerShell, the %CD% equivalent is [System.Environment]::CurrentDirectory.

Peter Mortensen's user avatar

answered Mar 18, 2016 at 16:09

nclord's user avatar

nclordnclord

1,2271 gold badge16 silver badges17 bronze badges

2

Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.

Try it! It’s safe to use and is awesome!

Peter Mortensen's user avatar

answered Feb 17, 2016 at 4:10

Netorica's user avatar

NetoricaNetorica

18.1k17 gold badges72 silver badges108 bronze badges

1

  • Command line changes will not be permanent and will be lost when the console closes.
  • The path works like first comes first served.
  • You may want to override other already included executables. For instance, if you already have another version on your path and you want to add different version without making a permanent change on path, you should put the directory at the beginning of the command.

To override already included executables;

set PATH=C:xamppphp;%PATH%;

Peter Mortensen's user avatar

answered Sep 6, 2016 at 14:37

hevi's user avatar

hevihevi

2,3501 gold badge32 silver badges51 bronze badges

Use pathed from gtools.

It does things in an intuitive way. For example:

pathed /REMOVE "c:myfolder"
pathed /APPEND "c:myfolder"

It shows results without the need to spawn a new cmd!

Peter Mortensen's user avatar

answered Mar 19, 2019 at 9:37

womd's user avatar

womdwomd

2,97325 silver badges19 bronze badges

1

Regarding point 2, I’m using a simple batch file that is populating PATH or other environment variables for me. Therefore, there isn’t any pollution of environment variables by default. This batch file is accessible from everywhere so I can type:

mybatchfile

Output:

-- Here all environment variables are available

And:

php file.php

Peter Mortensen's user avatar

answered Oct 30, 2015 at 14:22

Grzegorz Gajos's user avatar

3

Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the «help» outlines (that can be viewed when typing ‘command /?’ on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.

On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated… ).

The best SETX syntax usage that worked for me:

SETX PATH "%PATH%;C:pathtowherethecommandresides"

where any equal sign ‘=’ should be avoided, and don’t you worry about spaces! There isn’t any need to insert any more quotation marks for a path that contains spaces inside it — the split sign ‘;’ does the job.

The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ‘;’) to the existing values.

Peter Mortensen's user avatar

answered Nov 22, 2016 at 20:34

such_ke_nasdeeq's user avatar

1

If you run the command cmd, it will update all system variables for that command window.

answered Oct 17, 2018 at 2:06

Pranav Sharma's user avatar

1

In a command prompt you tell Cmd to use Windows Explorer’s command line by prefacing it with start.

So start Yourbatchname.

Note you have to register as if its name is batchfile.exe.

Programs and documents can be added to the registry so typing their name without their path in the Start — Run dialog box or shortcut enables Windows to find them.

This is a generic reg file. Copy the lines below to a new Text Document and save it as anyname.reg. Edit it with your programs or documents.

In paths, use \ to separate folder names in key paths as regedit uses a single to separate its key names. All reg files start with REGEDIT4. A semicolon turns a line into a comment. The @ symbol means to assign the value to the key rather than a named value.

The file doesn’t have to exist. This can be used to set Word.exe to open Winword.exe.

Typing start batchfile will start iexplore.exe.

REGEDIT4
;The bolded name below is the name of the document or program, <filename>.<file extension>

[HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionApp PathsBatchfile.exe]

; The @ means the path to the file is assigned to the default value for the key.
; The whole path in enclosed in a quotation mark ".

@=""C:\Program Files\Internet Explorer\iexplore.exe""

; Optional Parameters. The semicolon means don't process the line. Remove it if you want to put it in the registry

; Informs the shell that the program accepts URLs.

;"useURL"="1"

; Sets the path that a program will use as its' default directory. This is commented out.

;"Path"="C:\Program Files\Microsoft Office\Office\"

You’ve already been told about path in another answer. Also see doskey /? for cmd macros (they only work when typing).

You can run startup commands for CMD. From Windows Resource Kit Technical Reference

AutoRun

HKCUSoftwareMicrosoftCommand Processor

Data type Range Default value
REG_SZ  list of commands  There is no default value for this entry.

Description

Contains commands which are executed each time you start Cmd.exe.

Peter Mortensen's user avatar

answered Dec 21, 2016 at 1:08

A better alternative to Control Panel is to use this freeware program from SourceForge called Pathenator.

However, it only works for a system that has .NET 4.0 or greater such as Windows 7, Windows 8, or Windows 10.

Peter Mortensen's user avatar

answered Aug 28, 2017 at 1:24

Bimo's user avatar

BimoBimo

5,5972 gold badges35 silver badges57 bronze badges

0

As trivial as it may be, I had to restart Windows when faced with this problem.

I am running Windows 7 x64. I did a manual update to the system PATH variable. This worked okay if I ran cmd.exe from the stat menu. But if I type «cmd» in the Windows Explorer address bar, it seems to load the PATH from elsewhere, which doesn’t have my manual changes.

(To avoid doubt — yes, I did close and rerun cmd a couple of times before I restarted and it didn’t help.)

Peter Mortensen's user avatar

answered Oct 20, 2019 at 18:03

svinec's user avatar

svinecsvinec

6298 silver badges9 bronze badges

3

The below solution worked perfectly.

Try the below command in your Windows terminal.

setx PATH "C:myfolder;%PATH%"

SUCCESS: Specified value was saved.

You can refer to more on here.

Peter Mortensen's user avatar

answered Jun 5, 2021 at 13:42

Surendra Babu Parchuru's user avatar

Use these commands in the Bash shell on Windows to append a new location to the PATH variable

PATH=$PATH:/path/to/mydir

Or prepend this location

PATH=/path/to/mydir:$PATH

In your case, for instance, do

PATH=$PATH:C:xamppphp

You can echo $PATH to see the PATH variable in the shell.

Peter Mortensen's user avatar

answered Sep 1, 2021 at 6:48

kiriloff's user avatar

kiriloffkiriloff

25.2k36 gold badges143 silver badges222 bronze badges

1

  1. I have installed PHP that time. I extracted php-7***.zip into C:php</i>

  2. Back up my current PATH environment variable: run cmd, and execute command: path >C:path-backup.txt

  3. Get my current path value into C:path.txt file (the same way)

  4. Modify path.txt (sure, my path length is more than 1024 characters, and Windows is running few years)

  • I have removed duplicates paths in there, like ‘C:Windows; or C:WindowsSystem32; or C:WindowsSystem32Wbem; — I’ve got twice.
  • Remove uninstalled programs paths as well. Example: C:Program FilesNonExistSoftware;
  • This way, my path string length < 1024 :)))
  • at the end of the path string, add ;C:php
  • Copy path value only into buffer with framed double quotes! Example: «C:Windows;****;C:php» No PATH= should be there!!!
  1. Open Windows PowerShell as Administrator (e.g., Win + X).

  2. Run command:

    setx path "Here you should insert string from buffer (new path value)"

  3. Rerun your terminal (I use «Far Manager») and check:

    php -v

Peter Mortensen's user avatar

answered Oct 24, 2018 at 20:50

Serb's user avatar

SerbSerb

214 bronze badges

How to open the Environment Variables window from cmd.exe/Run… dialog

  • SystemPropertiesAdvanced and click «Environment Variables», no UAC
  • rundll32 sysdm.cpl,EditEnvironmentVariables direct, might trigger UAC

Via Can the environment variables tool in Windows be launched directly? on Server Fault.

How to open the Environment Variables window from Explorer

  1. right-click on «This PC»
  2. Click on «Properties»
  3. On the left panel of the window that pops up, click on «Advanced System Settings»
  4. Click on the «Advanced» tab
  5. Click on «Environment Variables» button at the bottom of the window

You can also search for Variables in the Start menu search.

Reference images how the Environment Variables window looks like:

Windows 10

Environment Variables window on Windows 10
via

Windows 7

Environment Variables window on Windows 7
via

Windows XP

Environment Variables window on Windows
via

On Windows 10, I was able to search for set path environment variable and got these instructions:

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation panel.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below:

C:Program Files;C:Winnt;C:WinntSystem32

The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.

answered Nov 12, 2020 at 1:38

Janin's user avatar

JaninJanin

2721 gold badge2 silver badges7 bronze badges

Содержание

Введение
Для чего используется
Пример
Добавить директорию в PATH
Изучить содержимое PATH
Ошибки
Postgesql
Похожие статьи

Введение

Если Вам нужно настроить PATH в Linux — перейдите

сюда

Для чего используется

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

Искать по всему жёсткому диску было бы слишком долго, поэтому поиск
осуществляется только по некоторым директориям.

Список этих особых директорий хранится в системной переменной PATH.

Пример

Предположим, что возникла необходимость запускать какую-то программу, например

Firefox

, непосредственно из командной строки.

Без предварительной подготовки ввод Firefox в консоль выдаст ошибку.

C:Usersa>firefox

‘firefox’ is not recognized as an internal or external command, operable program or batch file.

Чтобы решить эту проблему нужно добавить директорию с испоняемым файлом firefox в PATH

Добавить директорию в PATH

Быстрый способ перейти к редактированию PATH — нажать клавишу Win и ввести в поиск env

Env с сайта www.andreyolegovich.ru

Пошаговый способ:

Правый клик на Этот Компьютер (This PC) → Свойства (Properties)

Мой компьютер Свойства изображение с сайта www.andreyolegovich.ru

Дополнительные параметры системы (Advanced system settings)

Control Panel - All Control Panel Items - System изображение с сайта www.andreyolegovich.ru

Дополнительно (Advanced) → Переменные среды (Environment Variables)

Environment Variables изображение с сайта www.andreyolegovich.ru

Если хотите менять для всей системы, то в окошке «Переменные среды»
(System Variables)
найдите строку PATH в блоке
«Системные переменные» (System variables)
выделите кликом и нажмите кнопку «Изменить…» (Edit…)

Если хотите менять только для своего пользователя, то делайте это в блоке
«Переменные среды пользователя %USERNAME%» (User variables for %USERNAME%)

Environment Variables изображение с сайта www.andreyolegovich.ru

Создайте новый путь (New)

Path Environment Variable изображение с сайта www.andreyolegovich.ru

Введите адрес директории в которой лежит нужная программа. В нашем случае это

C:Program Files (x86)Mozilla Firefox

Path Environment Variable изображение с сайта www.andreyolegovich.ru

Перезапустите консоль или открываем новую и пишем там firefox.

C:Usersa>firefox

Браузер должен запуститься.

Изучить содержимое PATH

В

PowerShell

достаточно выполнить

echo $Env:Path

C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;

Или

Get-ChildItem Env:Path

Name Value
—- ——
Path C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPo…

В cmd.exe посмотреть список переменных
окружения можно выполнив команду

set

без параметров.

set

Выдача содержит системные переменные и переменные пользователя
а также дополнительную информацию. Содержимое PATH выделено зелёным.

результат выдачи команды set без параметров

Ошибки

-bash: syntax error near unexpected token `(‘

Скорее всего Вы пытаетесь добавить в unix PATH адрес из Windows, c пробелами, скобками и так далее.

Например:

andrey@olegovich-10:/usr/share$ export PATH=/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437:$PATH

-bash: syntax error near unexpected token `(‘

Для решения этой проблемы Вам нужно экранировать пробелы и скобки. Если импортируется много путей и ввод очень длинный —
немного проще записать PATH=$PATH:/путь , если Вам подходит запись в конец.

Также нужно помнить, что все лишние пробелы сломают импорт — для проверки можно сделать весь скрипт в одну строку
в текстовом редакторе.

Также стоит помнить, что если Вы работаете в

bash под Windows
,
то переменные окружения нужно задавать через Windows.

andrey@olegovich-10:/usr/share$ export PATH=$PATH:/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437

Postgesql

Приведу пример для использования psql из

bash под Windows

— это может пригодиться если Вы хотите временно добавить
путь к psql в PATH чтобы запустить

Postrgres

скрипт.

В моём случае

psql.exe

находится в папке C:Program FilesPostgreSQL12bin

PATH=$PATH:/mnt/c/Program Files/PostgreSQL/12/bin

Похожие статьи

Windows
Loudness Equalization
PowerShell
Посмотреть конец файла в PowerShell (аналог tail)
Создать новый файл в PowerShell (аналог touch)
Проверить контрольную сумму файла в PowerShell (аналог md5sum)
Windows Firewall
Remote Desktop Protocol
Драйверы в Windows
Режим разработчика в Windows 10
BASH в Windows 10
Telnet в Windows 10
Системная переменная PATH
Установка Windows на gpt диск
batch file
pstools
Удалённый рабочий стол
Горячие клавиши

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:dir1dir2 to the path variable, we can run the below command.

setx path "%path%;c:dir1dir2"

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>

Привет, посетитель сайта ZametkiNaPolyah.ru! Продолжим разбираться с командами и системными утилитами в операционной системе Windows 10, на этот раз будет разговор о переменной PATH в Windows. Всё дело в том, что системная переменная PATH дает нам возможность расширить список команд командной строки Windows, как это сделать, вы узнаете из этой публикации. Здесь мы с вами поговорим о назначении системной переменной PATH, а также разберемся с вопросом: как добавить  путь к исполняемому файлу в системную переменную PATH в операционных системах Windows 10, Windows 8 и Windows 7. Этой публикацией можно пользоваться как простой инструкцией по добавлению значений в переменную PATH для Windows.

Если вам интересна тема компьютерных сетей, то в блоге уже практически закончена первая часть курса по основам компьютерных сетей, можете ознакомиться с ее содержимым. И вот здесь можно получить немного информации о самом курсе.

Что такое переменная Path и зачем она нужна в Windows. Зачем нужно добавлять путь?

Содержание статьи:

  • Что такое переменная Path и зачем она нужна в Windows. Зачем нужно добавлять путь?
  • Как добавить путь к программе в системную переменную Path в Windows 10 и Windows 8
  • Как настроить переменную Path в Windows 7
  • Выводы

PATH – это системная переменная окружения Unix-подобных (например, Linux Mint) операционных систем, а также операционных систем семейства Windows. В переменной PATH нет ничего сложно и хитрого, это обыкновенный список папок и каталогов, в которых лежат исполняемые файлы (программы). Программы, путь к исполняемым файлом которых задан в системной переменной PATH, могут быть исполнены (запущены) непосредственно из командной строки Windows и из любого места вашей файловой системы (в Linux тоже есть командная строка, но ее лучше называть эмулятор терминала).

Давайте лучше посмотрим на примере зачем нужна переменная PATH в операционных системах семейства Windows (как, впрочем, и в других семействах). Смотреть будем на примере сторонней утилиты командной строки Windows tracetcp.exe. Она у меня установлена по следующему пути: c:Program Filestracetcp. Запустим командую строку Windows и попробуем выполнить команду tracetcp.

Пробуем запустить стороннюю утилиту командной строки Windows

Пробуем запустить стороннюю утилиту командной строки Windows

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

Поскольку мы находились в папке, отличной от той, где находится файл tracetcp.exe, а пути в переменной PATH к этому файлу не оказалось, командная строка просто не смогла его найти, чтобы исполнить, давайте всё-таки его запустим, для этого нужно будет перейти в папку c:Program Filestracetcp при помощи команды cd (в операционных системах Linux тоже есть команда cd и работает она аналогично), а затем запустить утилиту.

Запуск исполняемого файла в командной строке Windows

Запуск исполняемого файла в командной строке Windows

Теперь командная строка Windows смогла запустить нашу утилиту, поскольку смогла найти исполняемый файл tracetcp.exe, но каждый раз переходить в папку, где лежит исполняемый файл или каждый раз указывать абсолютный путь к исполняемому файлу — это очень неудобно, будет гораздо лучше, если мы укажем путь к исполняемому файлу в переменной PATH, тогда командная строка будет самостоятельно его находить в любое время и в любом месте.

Исполняемый файл был запущен, поскольку путь до него был добавлен в системную переменную Path

Исполняемый файл был запущен, поскольку путь до него был добавлен в системную переменную Path

На рисунке выше показано, что командная строка смогла запустить приложение из домашней папки пользователя, но это лишь благодаря тому, что я добавил путь исполняемому файлу в переменную PATH, теперь команда tracetcp будет работать из любой другой папки. Утилита tracetcp довольно простое приложение, представляющее собой один исполняемый файл — tracetcp.exe, можно было бы не прописывать путь в переменную PATH, а просто скопировать этот файл в папку System32, но устанавливать сторонние и непроверенные приложения, не требующие наличия файлов в System32, не самая хорошая и безопасная затея. В Windows лучше потратить немного времени на то, чтобы добавить путь к файлу в переменную PATH, о том как это сделать мы и поговорим ниже, рассмотрев этот процесс для операционных систем Windows 10, Windows 8 и Windows 7.

Как добавить путь к программе в системную переменную Path в Windows 10 и Windows 8

Добавление пути к программе в системную переменную PATH в операционных системах Windows 10 и Windows 8 делается по одному алгоритму, показывать я буду на примере Windows 10, так как восьмерки под рукой нет. Ранее мы уже видели, что небольшая утилита tracetcp запускалась из командной строки Windows только в том случае, если мы переходили в ту папку, в которую она установлена. Но это легко исправить, просто добавив полный путь к исполняемому файлу tracetcp.exe в системную переменную PATH. Давайте это и сделаем. Описывать процесс добавления значения в переменную PATH буду буквально по шагам и с демонстрацией скриншотов окон в Windows 10. Хотя сперва я напишу сам алгоритм, если его не хватит, то обратитесь к скриншотам ниже:

  1. Открываем поиск и пишем: «Система» или «Панель управления».
  2. Появится окно, в левом верхнем углу которого есть небольшое меню и пункт «Дополнительные параметры системы».
  3. Появится окно поменьше, в нижнем правом углу есть кнопка «Переменные среды…».
  4. Откроется окно управления переменными средами в Windows 10.
  5. Нас интересует переменная PATH, которая находится в разделе «Системные переменные», нажимаем на нее два раза.
  6. Появится окно для редактирования значений переменной PATH, чтобы добавить новое значение воспользуйтесь кнопкой «Создать».
  7. Подтвердите добавление нового значения в переменную PATH нажатием кнопки «Ок» и закройте все остальные окна.
  8. Если во время редактирования переменной PATH у вас была запущена командная строка Windows, то закройте ее и откройте заново, чтобы cmd.exe прочитала новое значение переменной PATH.

Открываем поиск Windows и в форму пишем: «Система» или «Панель управления». В результате вы должны увидеть примерно такой результат, как показано на рисунке ниже.

Используем поиск Windows, ищем по ключевому слову Система

Используем поиск Windows, ищем по ключевому слову Система

После того, как вы нажмете на кнопку «Система», у вас появится окно, в левой части которого есть небольшое меню, самым нижним пунктом этого меню будет «Дополнительные параметры системы».

Чтобы добавить значение в переменную PATH переходим во вкладку Дополнительные параметры системы

Чтобы добавить значение в переменную PATH переходим во вкладку Дополнительные параметры системы

После перехода у вас появится окно поменьше, в этом окне нас интересует вкладка «Дополнительно». В правом нижнем углу есть кнопка «Переменные среды…», на нее и нажимаем.

Нажимаем на кнопку Переменные среды

Нажимаем на кнопку Переменные среды

Появится еще одно окно, которое позволяет управлять системными переменными Windows 10. Обратите внимание: в это окно разделено на две части, в верхней части происходит управление переменными среды для текущего пользователя, в нижней части расположены системные переменные.

В разделе Системные перемененные ищем переменную PATH

В разделе Системные перемененные ищем переменную PATH

В данном случае нас будет интересовать переменная Path, которая находится в разделе «Системные переменные», кликаем на нее два раза, у нас появляется окно, которое позволяет удалять, добавлять и редактировать значения системной переменной Path в Windows 10 и Windows 8. Нам осталось выполнить два действия: нажать на кнопку создать, в появившуюся активную форму вписать путь к файлу tracetcp.exe и подтвердить свои действия нажатием клавиши «Ок».

Дбовляем путь к исполняемому файлу в системную переменную PATH в Windows 10

Дбовляем путь к исполняемому файлу в системную переменную PATH в Windows 10

Закройте все остальные окна. Если у вас была открыта командная строка, вы можете убедиться в том, что она не увидела новое значение переменной PATH, попробуйте выполнить tracetcp из корня диска C, ничего не сработает. Когда вы добавляете новый путь в переменную PATH, программе cmd.exe нужно перечитать значения этой переменной, самый простой способ заключается в том, чтобы закрыть и заново открыть командую строку. Теперь команда tracetcp работает из любой папки, аналогично можно поступать и с другими программами командной строки, которые вы устанавливаете в Windows.

Как настроить переменную Path в Windows 7

К сожалению, у меня не осталось скриншотов, на которых можно было бы продемонстрировать добавление пути в системную переменную PATH на Windows 7, поэтому здесь будет только пошаговый алгоритм добавления значения в переменную PATH:

  1. На вашем рабочем столе есть икнока с названием «Компьютер» или «Мой компьютер», нажмите на нее правой кнопкой мыши.
  2. Появится контекстное меню, в самом низу которого есть пункт «Свойства», выберете его.
  3. Перед вам развернется окно, в котором есть пункт меню «Дополнительные параметры системы», его и выбираем.
  4. В этом окне будет кнопка «Переменные среды», жмем на нее.
  5. У нас появляется окно управления системными переменными в Windows 7, внизу которого есть список переменных, среди которого нужно найти переменную PATH.
  6. Если такой переменной нет, то ее нужно создать, воспользовавшись кнопкой создать: у вас появится окно, в котором нужно будет вписать имя новой переменной, в нашем случае это Path.
  7. Если переменная PATH есть, то ее нужно выделить левой кнопкой мыши и нажать на кнопку изменить: появится небольшое окошко с двумя формами для ввода: верхняя форма содержит имя переменной — это Path. В нижней форме указаны абсолютные пути до исполняемых файлов различных программ, выглядет это примерно так: d:Program Filesapplication1;d:Program Filesapplication2;d:Program Filesaplication3; и так далее, чтобы добавить еще одно значение переместитесь в конец строки, убедитесь, что последним символом является «;» (именно этот символ является разделителем), впишите путь к исполняемому файлу (в моем случае он выглядел бы так: с:Program Filestracetcp) и в конце добавьте точку с запятой.
  8. Подтвердите свои действия нажатием кнопки «Ок» и закройте другие окна.

Как видите, настроить переменную PATH в Windows 7 не так уж и сложно.

Выводы

Вы этой статье мы разобрались с назначение системной переменной PATH и отметили, что в каждой операционной системе оно одинаковое и заключается в том, что переменная PATH является списком каталогов, в котором хранятся исполняемые файлы, если путь к исполняемому файлу есть в переменной PATH, то он может быть исполнен из командной строки операционной системы. Также мы разобрались с тем, как прописать путь к исполняемому файлу в операционных системах Windows 10, 8, 7.

Переменные среды Windows 11 и Windows 10Настройка переменных среды Windows может помочь сократить время, необходимое для набора команд в командной строке или, если вы часто пишете скрипты для собственных задач, сделать их более читаемыми. В большинстве случаев обычные пользователи добавляют записи в системную переменную среды PATH, хотя бывают и другие задачи.

В этой пошаговой инструкции базовая информация о том, как открыть переменные среды Windows 11 и Windows 10, создать или отредактировать их.

Что такое переменные среды

Переменные среды в Windows — записи о расположении системных папок, свойствах системы и другие, которые доступны для любой программы или скрипта.

Одна из наиболее часто используемых переменных среды — PATH, указывающая на папки, в которых выполняется поиск файлов, вызываемых в командной строке, терминале Windows, файле bat или из других источников. В качестве примера её назначения:

  • Если вы откроете командную строку (или диалоговое окно «Выполнить»), введёте regedit и нажмете Enter — вы сможете запустить редактор реестра, не указывая полный путь к файлу regedit.exe, поскольку путь C:Windows добавлен в переменную среды Path.
  • Если же тем же образом в командной строке написать имя программы, путь к которой не добавлен в Path (chrome.exe, adb.exe, pip и другие), вы получите сообщение «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом».

Если предположить, что вы часто используете команды adb.exe (например, для установки приложений Android в Windows 11), pip install (для установки пакетов Python) или любые другие то для того, чтобы не писать каждый раз полный путь к этим файлам, имеет смысл добавить эти пути в переменные среды.

Также вы можете добавлять и иные переменные среды (не обязательно содержащие пути), а в дальнейшем получать и использовать их значения в сценариях BAT (командной строки) или PowerShell. Пример получения и отображения значения системной переменной PATH для обоих случаев:

echo %PATH%
echo $Env:PATH

Получить список всех переменных среды в командной строке и PowerShell соответственно можно следующими командами:

set
ls env:

Редактирование переменных среды Windows 11/10

Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.

  1. Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter. Открыть изменение переменных среды в Windows
  2. На вкладке «Дополнительно» нажмите кнопку «Переменные среды…» Переменные среды в параметрах системы Windows
  3. В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»). Создание и изменение переменных среды Windows
  4. Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы. Изменение переменно PATH
  5. Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой». Изменение имени и значения системной переменной среды
  6. При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.

После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались.

I am trying to add C:xamppphp to my system PATH environment variable in Windows.

I have already added it using the Environment Variables dialog box.

But when I type into my console:

C:>path

it doesn’t show the new C:xamppphp directory:

PATH=D:Program FilesAutodeskMaya2008bin;C:Ruby192bin;C:WINDOWSsystem32;C:WINDOWS;
C:WINDOWSSystem32Wbem;C:PROGRA~1DISKEE~2DISKEE~1;c:Program FilesMicrosoft SQL
Server90Toolsbinn;C:Program FilesQuickTimeQTSystem;D:Program FilesTortoiseSVNbin
;D:Program FilesBazaar;C:Program FilesAndroidandroid-sdktools;D:Program Files
Microsoft Visual StudioCommonToolsWinNT;D:Program FilesMicrosoft Visual StudioCommon
MSDev98Bin;D:Program FilesMicrosoft Visual StudioCommonTools;D:Program Files
Microsoft Visual StudioVC98bin

I have two questions:

  1. Why did this happen? Is there something I did wrong?
  2. Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?

Peter Mortensen's user avatar

asked Mar 3, 2012 at 12:58

Netorica's user avatar

8

Option 1

After you change PATH with the GUI, close and reopen the console window.

This works because only programs started after the change will see the new PATH.

Option 2

This option only affects your current shell session, not the whole system. Execute this command in the command window you have open:

set PATH=%PATH%;C:yourpathhere

This command appends C:yourpathhere to the current PATH. If your path includes spaces, you do not need to include quote marks.

Breaking it down:

  • set – A command that changes cmd’s environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:yourpathhere – The %PATH% part expands to the current value of PATH, and ;C:yourpathhere is then concatenated to it. This becomes the new PATH.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:03

JimR's user avatar

JimRJimR

15.1k2 gold badges20 silver badges26 bronze badges

12

WARNING: This solution may be destructive to your PATH, and the stability of your system. As a side effect, it will merge your user and system PATH, and truncate PATH to 1024 characters. The effect of this command is irreversible. Make a backup of PATH first. See the comments for more information.

Don’t blindly copy-and-paste this. Use with caution.

You can permanently add a path to PATH with the setx command:

setx /M path "%path%;C:yourpathhere"

Remove the /M flag if you want to set the user PATH instead of the system PATH.

Notes:

  • The setx command is only available in Windows 7 and later.
  • You should run this command from an elevated command prompt.

  • If you only want to change it for the current session, use set.

StayOnTarget's user avatar

StayOnTarget

10.9k10 gold badges49 silver badges75 bronze badges

answered Feb 28, 2015 at 5:12

Nafscript's user avatar

NafscriptNafscript

4,9572 gold badges16 silver badges15 bronze badges

15

This only modifies the registry. An existing process won’t use these values. A new process will do so if it is started after this change and doesn’t inherit the old environment from its parent.

You didn’t specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:23

Hans Passant's user avatar

Hans PassantHans Passant

913k145 gold badges1670 silver badges2507 bronze badges

6

You don’t need any set or setx command. Simply open the terminal and type:

PATH

This shows the current value of PATH variable. Now you want to add directory to it? Simply type:

PATH %PATH%;C:xamppphp

If for any reason you want to clear the PATH variable (no paths at all or delete all paths in it), type:

PATH ;

Update

Like Danial Wilson noted in comment below, it sets the path only in the current session. To set the path permanently, use setx but be aware, although that sets the path permanently, but not in the current session, so you have to start a new command line to see the changes. More information is here.

To check if an environmental variable exist or see its value, use the ECHO command:

echo %YOUR_ENV_VARIABLE%

Peter Mortensen's user avatar

answered Jul 1, 2015 at 15:11

zar's user avatar

zarzar

10.9k13 gold badges90 silver badges171 bronze badges

6

I would use PowerShell instead!

To add a directory to PATH using PowerShell, do the following:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$xampp_path = "C:xamppphp"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path")

To set the variable for all users, machine-wide, the last line should be like:

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

In a PowerShell script, you might want to check for the presence of your C:xamppphp before adding to PATH (in case it has been previously added). You can wrap it in an if conditional.

So putting it all together:

$PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
$xampp_path = "C:xamppphp"
if( $PATH -notlike "*"+$xampp_path+"*" ){
    [Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path", "Machine")
}

Better still, one could create a generic function. Just supply the directory you wish to add:

function AddTo-Path{
param(
    [string]$Dir
)

    if( !(Test-Path $Dir) ){
        Write-warning "Supplied directory was not found!"
        return
    }
    $PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
    if( $PATH -notlike "*"+$Dir+"*" ){
        [Environment]::SetEnvironmentVariable("PATH", "$PATH;$Dir", "Machine")
    }
}

You could make things better by doing some polishing. For example, using Test-Path to confirm that your directory actually exists.

Mariano Desanze's user avatar

answered Mar 17, 2015 at 20:24

Ifedi Okonkwo's user avatar

Ifedi OkonkwoIfedi Okonkwo

3,3064 gold badges31 silver badges45 bronze badges

4

Safer SETX

Nod to all the comments on the @Nafscript’s initial SETX answer.

  • SETX by default will update your user path.
  • SETX ... /M will update your system path.
  • %PATH% contains the system path with the user path appended

Warnings

  1. Backup your PATHSETX will truncate your junk longer than 1024 characters
  2. Don’t call SETX %PATH%;xxx — adds the system path into the user path
  3. Don’t call SETX %PATH%;xxx /M — adds the user path into the system path
  4. Excessive batch file use can cause blindness1

The ss64 SETX page has some very good examples. Importantly it points to where the registry keys are for SETX vs SETX /M

User Variables:

HKCUEnvironment

System Variables:

HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment

Usage instructions

Append to User PATH

append_user_path.cmd

@ECHO OFF
REM usage: append_user_path "path"
SET Key="HKCUEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > user_path_bak.txt
SETX PATH "%CurrPath%";%1

Append to System PATH

append_system_path.cmd. Must be run as administrator.

(It’s basically the same except with a different Key and the SETX /M modifier.)

@ECHO OFF
REM usage: append_system_path "path"
SET Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > system_path_bak.txt
SETX PATH "%CurrPath%";%1 /M

Alternatives

Finally there’s potentially an improved version called SETENV recommended by the ss64 SETX page that splits out setting the user or system environment variables.


Example

Here’s a full example that works on Windows 7 to set the PATH environment variable system wide. The example detects if the software has already been added to the PATH before attempting to change the value. There are a number of minor technical differences from the examples given above:

@echo off
set OWNPATH=%~dp0
set PLATFORM=mswin

if defined ProgramFiles(x86)                        set PLATFORM=win64
if "%PROCESSOR_ARCHITECTURE%"=="AMD64"              set PLATFORM=win64
if exist "%OWNPATH%textexmf-mswinbincontext.exe" set PLATFORM=mswin
if exist "%OWNPATH%textexmf-win64bincontext.exe" set PLATFORM=win64

rem Check if the PATH was updated previously
echo %PATH% | findstr "texmf-%PLATFORM%" > nul

rem Only update the PATH if not previously updated
if ERRORLEVEL 1 (
  set Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
  for /F "USEBACKQ tokens=2*" %%A in (`reg query %%Key%% /v PATH`) do (
    if not "%%~B" == "" (
      rem Preserve the existing PATH
      echo %%B > currpath.txt

      rem Update the current session
      set PATH=%PATH%;%OWNPATH%textexmf-%PLATFORM%bin
      
      rem Persist the PATH environment variable
      setx PATH "%%B;%OWNPATH%textexmf-%PLATFORM%bin" /M
    )
  )
)

1. Not strictly true

Dave Jarvis's user avatar

Dave Jarvis

29.9k39 gold badges177 silver badges310 bronze badges

answered Dec 29, 2016 at 12:04

icc97's user avatar

icc97icc97

10.6k8 gold badges68 silver badges88 bronze badges

0

Handy if you are already in the directory you want to add to PATH:

set PATH=%PATH%;%CD%

It works with the standard Windows cmd, but not in PowerShell.

For PowerShell, the %CD% equivalent is [System.Environment]::CurrentDirectory.

Peter Mortensen's user avatar

answered Mar 18, 2016 at 16:09

nclord's user avatar

nclordnclord

1,2271 gold badge16 silver badges17 bronze badges

2

Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.

Try it! It’s safe to use and is awesome!

Peter Mortensen's user avatar

answered Feb 17, 2016 at 4:10

Netorica's user avatar

NetoricaNetorica

18.1k17 gold badges72 silver badges108 bronze badges

1

  • Command line changes will not be permanent and will be lost when the console closes.
  • The path works like first comes first served.
  • You may want to override other already included executables. For instance, if you already have another version on your path and you want to add different version without making a permanent change on path, you should put the directory at the beginning of the command.

To override already included executables;

set PATH=C:xamppphp;%PATH%;

Peter Mortensen's user avatar

answered Sep 6, 2016 at 14:37

hevi's user avatar

hevihevi

2,3501 gold badge32 silver badges51 bronze badges

Use pathed from gtools.

It does things in an intuitive way. For example:

pathed /REMOVE "c:myfolder"
pathed /APPEND "c:myfolder"

It shows results without the need to spawn a new cmd!

Peter Mortensen's user avatar

answered Mar 19, 2019 at 9:37

womd's user avatar

womdwomd

2,97325 silver badges19 bronze badges

1

Regarding point 2, I’m using a simple batch file that is populating PATH or other environment variables for me. Therefore, there isn’t any pollution of environment variables by default. This batch file is accessible from everywhere so I can type:

mybatchfile

Output:

-- Here all environment variables are available

And:

php file.php

Peter Mortensen's user avatar

answered Oct 30, 2015 at 14:22

Grzegorz Gajos's user avatar

3

Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the «help» outlines (that can be viewed when typing ‘command /?’ on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.

On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated… ).

The best SETX syntax usage that worked for me:

SETX PATH "%PATH%;C:pathtowherethecommandresides"

where any equal sign ‘=’ should be avoided, and don’t you worry about spaces! There isn’t any need to insert any more quotation marks for a path that contains spaces inside it — the split sign ‘;’ does the job.

The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ‘;’) to the existing values.

Peter Mortensen's user avatar

answered Nov 22, 2016 at 20:34

such_ke_nasdeeq's user avatar

1

If you run the command cmd, it will update all system variables for that command window.

answered Oct 17, 2018 at 2:06

Pranav Sharma's user avatar

1

In a command prompt you tell Cmd to use Windows Explorer’s command line by prefacing it with start.

So start Yourbatchname.

Note you have to register as if its name is batchfile.exe.

Programs and documents can be added to the registry so typing their name without their path in the Start — Run dialog box or shortcut enables Windows to find them.

This is a generic reg file. Copy the lines below to a new Text Document and save it as anyname.reg. Edit it with your programs or documents.

In paths, use \ to separate folder names in key paths as regedit uses a single to separate its key names. All reg files start with REGEDIT4. A semicolon turns a line into a comment. The @ symbol means to assign the value to the key rather than a named value.

The file doesn’t have to exist. This can be used to set Word.exe to open Winword.exe.

Typing start batchfile will start iexplore.exe.

REGEDIT4
;The bolded name below is the name of the document or program, <filename>.<file extension>

[HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionApp PathsBatchfile.exe]

; The @ means the path to the file is assigned to the default value for the key.
; The whole path in enclosed in a quotation mark ".

@=""C:\Program Files\Internet Explorer\iexplore.exe""

; Optional Parameters. The semicolon means don't process the line. Remove it if you want to put it in the registry

; Informs the shell that the program accepts URLs.

;"useURL"="1"

; Sets the path that a program will use as its' default directory. This is commented out.

;"Path"="C:\Program Files\Microsoft Office\Office\"

You’ve already been told about path in another answer. Also see doskey /? for cmd macros (they only work when typing).

You can run startup commands for CMD. From Windows Resource Kit Technical Reference

AutoRun

HKCUSoftwareMicrosoftCommand Processor

Data type Range Default value
REG_SZ  list of commands  There is no default value for this entry.

Description

Contains commands which are executed each time you start Cmd.exe.

Peter Mortensen's user avatar

answered Dec 21, 2016 at 1:08

A better alternative to Control Panel is to use this freeware program from SourceForge called Pathenator.

However, it only works for a system that has .NET 4.0 or greater such as Windows 7, Windows 8, or Windows 10.

Peter Mortensen's user avatar

answered Aug 28, 2017 at 1:24

Bimo's user avatar

BimoBimo

5,5972 gold badges35 silver badges57 bronze badges

0

As trivial as it may be, I had to restart Windows when faced with this problem.

I am running Windows 7 x64. I did a manual update to the system PATH variable. This worked okay if I ran cmd.exe from the stat menu. But if I type «cmd» in the Windows Explorer address bar, it seems to load the PATH from elsewhere, which doesn’t have my manual changes.

(To avoid doubt — yes, I did close and rerun cmd a couple of times before I restarted and it didn’t help.)

Peter Mortensen's user avatar

answered Oct 20, 2019 at 18:03

svinec's user avatar

svinecsvinec

6298 silver badges9 bronze badges

3

The below solution worked perfectly.

Try the below command in your Windows terminal.

setx PATH "C:myfolder;%PATH%"

SUCCESS: Specified value was saved.

You can refer to more on here.

Peter Mortensen's user avatar

answered Jun 5, 2021 at 13:42

Surendra Babu Parchuru's user avatar

Use these commands in the Bash shell on Windows to append a new location to the PATH variable

PATH=$PATH:/path/to/mydir

Or prepend this location

PATH=/path/to/mydir:$PATH

In your case, for instance, do

PATH=$PATH:C:xamppphp

You can echo $PATH to see the PATH variable in the shell.

Peter Mortensen's user avatar

answered Sep 1, 2021 at 6:48

kiriloff's user avatar

kiriloffkiriloff

25.2k36 gold badges143 silver badges222 bronze badges

1

  1. I have installed PHP that time. I extracted php-7***.zip into C:php</i>

  2. Back up my current PATH environment variable: run cmd, and execute command: path >C:path-backup.txt

  3. Get my current path value into C:path.txt file (the same way)

  4. Modify path.txt (sure, my path length is more than 1024 characters, and Windows is running few years)

  • I have removed duplicates paths in there, like ‘C:Windows; or C:WindowsSystem32; or C:WindowsSystem32Wbem; — I’ve got twice.
  • Remove uninstalled programs paths as well. Example: C:Program FilesNonExistSoftware;
  • This way, my path string length < 1024 :)))
  • at the end of the path string, add ;C:php
  • Copy path value only into buffer with framed double quotes! Example: «C:Windows;****;C:php» No PATH= should be there!!!
  1. Open Windows PowerShell as Administrator (e.g., Win + X).

  2. Run command:

    setx path "Here you should insert string from buffer (new path value)"

  3. Rerun your terminal (I use «Far Manager») and check:

    php -v

Peter Mortensen's user avatar

answered Oct 24, 2018 at 20:50

Serb's user avatar

SerbSerb

214 bronze badges

How to open the Environment Variables window from cmd.exe/Run… dialog

  • SystemPropertiesAdvanced and click «Environment Variables», no UAC
  • rundll32 sysdm.cpl,EditEnvironmentVariables direct, might trigger UAC

Via Can the environment variables tool in Windows be launched directly? on Server Fault.

How to open the Environment Variables window from Explorer

  1. right-click on «This PC»
  2. Click on «Properties»
  3. On the left panel of the window that pops up, click on «Advanced System Settings»
  4. Click on the «Advanced» tab
  5. Click on «Environment Variables» button at the bottom of the window

You can also search for Variables in the Start menu search.

Reference images how the Environment Variables window looks like:

Windows 10

Environment Variables window on Windows 10
via

Windows 7

Environment Variables window on Windows 7
via

Windows XP

Environment Variables window on Windows
via

On Windows 10, I was able to search for set path environment variable and got these instructions:

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation panel.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below:

C:Program Files;C:Winnt;C:WinntSystem32

The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.

answered Nov 12, 2020 at 1:38

Janin's user avatar

JaninJanin

2721 gold badge2 silver badges7 bronze badges

I am trying to add C:xamppphp to my system PATH environment variable in Windows.

I have already added it using the Environment Variables dialog box.

But when I type into my console:

C:>path

it doesn’t show the new C:xamppphp directory:

PATH=D:Program FilesAutodeskMaya2008bin;C:Ruby192bin;C:WINDOWSsystem32;C:WINDOWS;
C:WINDOWSSystem32Wbem;C:PROGRA~1DISKEE~2DISKEE~1;c:Program FilesMicrosoft SQL
Server90Toolsbinn;C:Program FilesQuickTimeQTSystem;D:Program FilesTortoiseSVNbin
;D:Program FilesBazaar;C:Program FilesAndroidandroid-sdktools;D:Program Files
Microsoft Visual StudioCommonToolsWinNT;D:Program FilesMicrosoft Visual StudioCommon
MSDev98Bin;D:Program FilesMicrosoft Visual StudioCommonTools;D:Program Files
Microsoft Visual StudioVC98bin

I have two questions:

  1. Why did this happen? Is there something I did wrong?
  2. Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?

Peter Mortensen's user avatar

asked Mar 3, 2012 at 12:58

Netorica's user avatar

8

Option 1

After you change PATH with the GUI, close and reopen the console window.

This works because only programs started after the change will see the new PATH.

Option 2

This option only affects your current shell session, not the whole system. Execute this command in the command window you have open:

set PATH=%PATH%;C:yourpathhere

This command appends C:yourpathhere to the current PATH. If your path includes spaces, you do not need to include quote marks.

Breaking it down:

  • set – A command that changes cmd’s environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:yourpathhere – The %PATH% part expands to the current value of PATH, and ;C:yourpathhere is then concatenated to it. This becomes the new PATH.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:03

JimR's user avatar

JimRJimR

15.1k2 gold badges20 silver badges26 bronze badges

12

WARNING: This solution may be destructive to your PATH, and the stability of your system. As a side effect, it will merge your user and system PATH, and truncate PATH to 1024 characters. The effect of this command is irreversible. Make a backup of PATH first. See the comments for more information.

Don’t blindly copy-and-paste this. Use with caution.

You can permanently add a path to PATH with the setx command:

setx /M path "%path%;C:yourpathhere"

Remove the /M flag if you want to set the user PATH instead of the system PATH.

Notes:

  • The setx command is only available in Windows 7 and later.
  • You should run this command from an elevated command prompt.

  • If you only want to change it for the current session, use set.

StayOnTarget's user avatar

StayOnTarget

10.9k10 gold badges49 silver badges75 bronze badges

answered Feb 28, 2015 at 5:12

Nafscript's user avatar

NafscriptNafscript

4,9572 gold badges16 silver badges15 bronze badges

15

This only modifies the registry. An existing process won’t use these values. A new process will do so if it is started after this change and doesn’t inherit the old environment from its parent.

You didn’t specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.

Peter Mortensen's user avatar

answered Mar 3, 2012 at 13:23

Hans Passant's user avatar

Hans PassantHans Passant

913k145 gold badges1670 silver badges2507 bronze badges

6

You don’t need any set or setx command. Simply open the terminal and type:

PATH

This shows the current value of PATH variable. Now you want to add directory to it? Simply type:

PATH %PATH%;C:xamppphp

If for any reason you want to clear the PATH variable (no paths at all or delete all paths in it), type:

PATH ;

Update

Like Danial Wilson noted in comment below, it sets the path only in the current session. To set the path permanently, use setx but be aware, although that sets the path permanently, but not in the current session, so you have to start a new command line to see the changes. More information is here.

To check if an environmental variable exist or see its value, use the ECHO command:

echo %YOUR_ENV_VARIABLE%

Peter Mortensen's user avatar

answered Jul 1, 2015 at 15:11

zar's user avatar

zarzar

10.9k13 gold badges90 silver badges171 bronze badges

6

I would use PowerShell instead!

To add a directory to PATH using PowerShell, do the following:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$xampp_path = "C:xamppphp"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path")

To set the variable for all users, machine-wide, the last line should be like:

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

In a PowerShell script, you might want to check for the presence of your C:xamppphp before adding to PATH (in case it has been previously added). You can wrap it in an if conditional.

So putting it all together:

$PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
$xampp_path = "C:xamppphp"
if( $PATH -notlike "*"+$xampp_path+"*" ){
    [Environment]::SetEnvironmentVariable("PATH", "$PATH;$xampp_path", "Machine")
}

Better still, one could create a generic function. Just supply the directory you wish to add:

function AddTo-Path{
param(
    [string]$Dir
)

    if( !(Test-Path $Dir) ){
        Write-warning "Supplied directory was not found!"
        return
    }
    $PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine")
    if( $PATH -notlike "*"+$Dir+"*" ){
        [Environment]::SetEnvironmentVariable("PATH", "$PATH;$Dir", "Machine")
    }
}

You could make things better by doing some polishing. For example, using Test-Path to confirm that your directory actually exists.

Mariano Desanze's user avatar

answered Mar 17, 2015 at 20:24

Ifedi Okonkwo's user avatar

Ifedi OkonkwoIfedi Okonkwo

3,3064 gold badges31 silver badges45 bronze badges

4

Safer SETX

Nod to all the comments on the @Nafscript’s initial SETX answer.

  • SETX by default will update your user path.
  • SETX ... /M will update your system path.
  • %PATH% contains the system path with the user path appended

Warnings

  1. Backup your PATHSETX will truncate your junk longer than 1024 characters
  2. Don’t call SETX %PATH%;xxx — adds the system path into the user path
  3. Don’t call SETX %PATH%;xxx /M — adds the user path into the system path
  4. Excessive batch file use can cause blindness1

The ss64 SETX page has some very good examples. Importantly it points to where the registry keys are for SETX vs SETX /M

User Variables:

HKCUEnvironment

System Variables:

HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment

Usage instructions

Append to User PATH

append_user_path.cmd

@ECHO OFF
REM usage: append_user_path "path"
SET Key="HKCUEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > user_path_bak.txt
SETX PATH "%CurrPath%";%1

Append to System PATH

append_system_path.cmd. Must be run as administrator.

(It’s basically the same except with a different Key and the SETX /M modifier.)

@ECHO OFF
REM usage: append_system_path "path"
SET Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
FOR /F "usebackq tokens=2*" %%A IN (`REG QUERY %Key% /v PATH`) DO Set CurrPath=%%B
ECHO %CurrPath% > system_path_bak.txt
SETX PATH "%CurrPath%";%1 /M

Alternatives

Finally there’s potentially an improved version called SETENV recommended by the ss64 SETX page that splits out setting the user or system environment variables.


Example

Here’s a full example that works on Windows 7 to set the PATH environment variable system wide. The example detects if the software has already been added to the PATH before attempting to change the value. There are a number of minor technical differences from the examples given above:

@echo off
set OWNPATH=%~dp0
set PLATFORM=mswin

if defined ProgramFiles(x86)                        set PLATFORM=win64
if "%PROCESSOR_ARCHITECTURE%"=="AMD64"              set PLATFORM=win64
if exist "%OWNPATH%textexmf-mswinbincontext.exe" set PLATFORM=mswin
if exist "%OWNPATH%textexmf-win64bincontext.exe" set PLATFORM=win64

rem Check if the PATH was updated previously
echo %PATH% | findstr "texmf-%PLATFORM%" > nul

rem Only update the PATH if not previously updated
if ERRORLEVEL 1 (
  set Key="HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment"
  for /F "USEBACKQ tokens=2*" %%A in (`reg query %%Key%% /v PATH`) do (
    if not "%%~B" == "" (
      rem Preserve the existing PATH
      echo %%B > currpath.txt

      rem Update the current session
      set PATH=%PATH%;%OWNPATH%textexmf-%PLATFORM%bin
      
      rem Persist the PATH environment variable
      setx PATH "%%B;%OWNPATH%textexmf-%PLATFORM%bin" /M
    )
  )
)

1. Not strictly true

Dave Jarvis's user avatar

Dave Jarvis

29.9k39 gold badges177 silver badges310 bronze badges

answered Dec 29, 2016 at 12:04

icc97's user avatar

icc97icc97

10.6k8 gold badges68 silver badges88 bronze badges

0

Handy if you are already in the directory you want to add to PATH:

set PATH=%PATH%;%CD%

It works with the standard Windows cmd, but not in PowerShell.

For PowerShell, the %CD% equivalent is [System.Environment]::CurrentDirectory.

Peter Mortensen's user avatar

answered Mar 18, 2016 at 16:09

nclord's user avatar

nclordnclord

1,2271 gold badge16 silver badges17 bronze badges

2

Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.

Try it! It’s safe to use and is awesome!

Peter Mortensen's user avatar

answered Feb 17, 2016 at 4:10

Netorica's user avatar

NetoricaNetorica

18.1k17 gold badges72 silver badges108 bronze badges

1

  • Command line changes will not be permanent and will be lost when the console closes.
  • The path works like first comes first served.
  • You may want to override other already included executables. For instance, if you already have another version on your path and you want to add different version without making a permanent change on path, you should put the directory at the beginning of the command.

To override already included executables;

set PATH=C:xamppphp;%PATH%;

Peter Mortensen's user avatar

answered Sep 6, 2016 at 14:37

hevi's user avatar

hevihevi

2,3501 gold badge32 silver badges51 bronze badges

Use pathed from gtools.

It does things in an intuitive way. For example:

pathed /REMOVE "c:myfolder"
pathed /APPEND "c:myfolder"

It shows results without the need to spawn a new cmd!

Peter Mortensen's user avatar

answered Mar 19, 2019 at 9:37

womd's user avatar

womdwomd

2,97325 silver badges19 bronze badges

1

Regarding point 2, I’m using a simple batch file that is populating PATH or other environment variables for me. Therefore, there isn’t any pollution of environment variables by default. This batch file is accessible from everywhere so I can type:

mybatchfile

Output:

-- Here all environment variables are available

And:

php file.php

Peter Mortensen's user avatar

answered Oct 30, 2015 at 14:22

Grzegorz Gajos's user avatar

3

Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the «help» outlines (that can be viewed when typing ‘command /?’ on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.

On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated… ).

The best SETX syntax usage that worked for me:

SETX PATH "%PATH%;C:pathtowherethecommandresides"

where any equal sign ‘=’ should be avoided, and don’t you worry about spaces! There isn’t any need to insert any more quotation marks for a path that contains spaces inside it — the split sign ‘;’ does the job.

The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ‘;’) to the existing values.

Peter Mortensen's user avatar

answered Nov 22, 2016 at 20:34

such_ke_nasdeeq's user avatar

1

If you run the command cmd, it will update all system variables for that command window.

answered Oct 17, 2018 at 2:06

Pranav Sharma's user avatar

1

In a command prompt you tell Cmd to use Windows Explorer’s command line by prefacing it with start.

So start Yourbatchname.

Note you have to register as if its name is batchfile.exe.

Programs and documents can be added to the registry so typing their name without their path in the Start — Run dialog box or shortcut enables Windows to find them.

This is a generic reg file. Copy the lines below to a new Text Document and save it as anyname.reg. Edit it with your programs or documents.

In paths, use \ to separate folder names in key paths as regedit uses a single to separate its key names. All reg files start with REGEDIT4. A semicolon turns a line into a comment. The @ symbol means to assign the value to the key rather than a named value.

The file doesn’t have to exist. This can be used to set Word.exe to open Winword.exe.

Typing start batchfile will start iexplore.exe.

REGEDIT4
;The bolded name below is the name of the document or program, <filename>.<file extension>

[HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionApp PathsBatchfile.exe]

; The @ means the path to the file is assigned to the default value for the key.
; The whole path in enclosed in a quotation mark ".

@=""C:\Program Files\Internet Explorer\iexplore.exe""

; Optional Parameters. The semicolon means don't process the line. Remove it if you want to put it in the registry

; Informs the shell that the program accepts URLs.

;"useURL"="1"

; Sets the path that a program will use as its' default directory. This is commented out.

;"Path"="C:\Program Files\Microsoft Office\Office\"

You’ve already been told about path in another answer. Also see doskey /? for cmd macros (they only work when typing).

You can run startup commands for CMD. From Windows Resource Kit Technical Reference

AutoRun

HKCUSoftwareMicrosoftCommand Processor

Data type Range Default value
REG_SZ  list of commands  There is no default value for this entry.

Description

Contains commands which are executed each time you start Cmd.exe.

Peter Mortensen's user avatar

answered Dec 21, 2016 at 1:08

A better alternative to Control Panel is to use this freeware program from SourceForge called Pathenator.

However, it only works for a system that has .NET 4.0 or greater such as Windows 7, Windows 8, or Windows 10.

Peter Mortensen's user avatar

answered Aug 28, 2017 at 1:24

Bimo's user avatar

BimoBimo

5,5972 gold badges35 silver badges57 bronze badges

0

As trivial as it may be, I had to restart Windows when faced with this problem.

I am running Windows 7 x64. I did a manual update to the system PATH variable. This worked okay if I ran cmd.exe from the stat menu. But if I type «cmd» in the Windows Explorer address bar, it seems to load the PATH from elsewhere, which doesn’t have my manual changes.

(To avoid doubt — yes, I did close and rerun cmd a couple of times before I restarted and it didn’t help.)

Peter Mortensen's user avatar

answered Oct 20, 2019 at 18:03

svinec's user avatar

svinecsvinec

6298 silver badges9 bronze badges

3

The below solution worked perfectly.

Try the below command in your Windows terminal.

setx PATH "C:myfolder;%PATH%"

SUCCESS: Specified value was saved.

You can refer to more on here.

Peter Mortensen's user avatar

answered Jun 5, 2021 at 13:42

Surendra Babu Parchuru's user avatar

Use these commands in the Bash shell on Windows to append a new location to the PATH variable

PATH=$PATH:/path/to/mydir

Or prepend this location

PATH=/path/to/mydir:$PATH

In your case, for instance, do

PATH=$PATH:C:xamppphp

You can echo $PATH to see the PATH variable in the shell.

Peter Mortensen's user avatar

answered Sep 1, 2021 at 6:48

kiriloff's user avatar

kiriloffkiriloff

25.2k36 gold badges143 silver badges222 bronze badges

1

  1. I have installed PHP that time. I extracted php-7***.zip into C:php</i>

  2. Back up my current PATH environment variable: run cmd, and execute command: path >C:path-backup.txt

  3. Get my current path value into C:path.txt file (the same way)

  4. Modify path.txt (sure, my path length is more than 1024 characters, and Windows is running few years)

  • I have removed duplicates paths in there, like ‘C:Windows; or C:WindowsSystem32; or C:WindowsSystem32Wbem; — I’ve got twice.
  • Remove uninstalled programs paths as well. Example: C:Program FilesNonExistSoftware;
  • This way, my path string length < 1024 :)))
  • at the end of the path string, add ;C:php
  • Copy path value only into buffer with framed double quotes! Example: «C:Windows;****;C:php» No PATH= should be there!!!
  1. Open Windows PowerShell as Administrator (e.g., Win + X).

  2. Run command:

    setx path "Here you should insert string from buffer (new path value)"

  3. Rerun your terminal (I use «Far Manager») and check:

    php -v

Peter Mortensen's user avatar

answered Oct 24, 2018 at 20:50

Serb's user avatar

SerbSerb

214 bronze badges

How to open the Environment Variables window from cmd.exe/Run… dialog

  • SystemPropertiesAdvanced and click «Environment Variables», no UAC
  • rundll32 sysdm.cpl,EditEnvironmentVariables direct, might trigger UAC

Via Can the environment variables tool in Windows be launched directly? on Server Fault.

How to open the Environment Variables window from Explorer

  1. right-click on «This PC»
  2. Click on «Properties»
  3. On the left panel of the window that pops up, click on «Advanced System Settings»
  4. Click on the «Advanced» tab
  5. Click on «Environment Variables» button at the bottom of the window

You can also search for Variables in the Start menu search.

Reference images how the Environment Variables window looks like:

Windows 10

Environment Variables window on Windows 10
via

Windows 7

Environment Variables window on Windows 7
via

Windows XP

Environment Variables window on Windows
via

On Windows 10, I was able to search for set path environment variable and got these instructions:

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation panel.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below:

C:Program Files;C:Winnt;C:WinntSystem32

The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.

answered Nov 12, 2020 at 1:38

Janin's user avatar

JaninJanin

2721 gold badge2 silver badges7 bronze badges

Понравилась статья? Поделить с друзьями:
  • Windows ж?йесіні? бас?а ж?йелерден ?андай айырмашылы?ы бар
  • Windows как восстановить шрифты по умолчанию windows 7
  • Windows ж?йесіндегі экранны? е? кіші ?лшемі ?андай
  • Windows как войти в консоль восстановления windows xp
  • Windows каждый день обновления windows 10