Error vue : vue: command not found [duplicate] - windows

I have a one-line snippet that works perfectly in the command line, but fails and throws up errors when I run it as part of a batch script.
The below commands behaves as expected, deleting all empty subfolders in the folder.
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"
However, when put in a batch file like so...
FOR /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"
...it throws the standard error:
Sort is not recognised as an internal or external command
I've been experimenting for the last hour or so with and without escaping the pipe, changing the order of the options, looking up the documentation of both dir and sort, etc., but I've still not been able to figure out what's going on here. The rest of the batch file, which is only a few lines, works fine, and this is the only line in it that fails.

A) How does Windows command processor search for commands?
Windows command processor searches for a COMMAND to execute which
is not an internal command of cmd.exe and
is just specified with file name without file extension and without path
for a file matching the pattern command.* and having a file extension listed in local environment variable PATHEXT
first in current directory and
next in all directories of local environment variable PATH.
SORT and FIND and FINDSTR and ROBOCOPY and XCOPY and many more commands are not internal commands of cmd.exe. They are console applications installed with Windows located in directory %SystemRoot%\System32 having the file name sort.exe, find.exe, findstr.exe, robocopy.exe, xcopy.exe, ...
Such console applications available by default on Windows are called external commands to distinguish them better from console applications not installed with Windows operating system.
B) How is the environment variable PATH defined?
There are three types of PATH variables:
System PATH which is used for all accounts and stored in Windows registry under key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
User PATH which is used only for current account and stored in Windows registry under key:
HKEY_CURRENT_USER\Environment
Local PATH which is always a copy of the local PATH of parent process which started the current process.
Windows concatenates system and user PATH to local PATH for the Windows Explorer instance used as Windows desktop with the shortcuts on the desktop screen and the Windows start menu and the Windows taskbar as visible interface for the user called Windows shell from which users usually start programs.
The entire currently active environment variables list of running process is copied for the new process by Windows on starting a new process. The Windows kernel library function CreateProcess does this environment variables list copy from the memory of the current process to the memory of the new process on function parameter lpEnvironment (long pointer to environment) being a null pointer. One of the CreateProcess functions is always used on Windows on starting an executable from another executable.
The parent process cannot modify the environment variables of any child process nor can a child process modify the environment variables of its parent process.
This means once a process like cmd.exe was started for execution of a batch file, the process has its own set of environment variables which only the process itself can modify. No other process can modify the environment variables of an already running process.
C) What does the error message mean?
The error message
'...' is not recognized as an internal or external command,operable program or batch file.
always means that
the file name of a
console application
GUI application
script (batch file, PowerShell script, Perl script, VBScript, JScript, ...)
was specified for execution most likely without file extension and without (complete) path to the executable/script file and
Windows failed to find a file matching the pattern FileName.* with a file extension listed in currently active environment variable PATHEXT in current directory or any other directory in currently active environment variable PATH.
D) What are the possible reasons for this error message?
Typical reasons are:
1. The file name of the file to execute was specified wrong due to a typing mistake.
Check character by character the name of the command/executable.
2. The current directory is different to the directory containing the file to execute.
Run echo Current directory is: %CD% on command line or add this line to the batch file above the command line which fails to see what the current directory is.
3. The executable or script to run is not installed at all.
Verify the existence of the executable to run. Some installation packages work only if other packages like Java, NPM, PHP, etc. were installed before.
4. The directory of the file to execute is not in PATH at all.
Open in Windows Control Panel the System settings window, click on Advanced system settings on left side, click on button Environment Variables and look in both lists for Path and their values. By default Path exists only in list of System variables.
5. A running process/application was not restarted after modification of system or user PATH.
A modification of system PATH or user PATH with command setx or via Control Panel – System and Security – System – Advanced system settings - Environment Variables was made by the user or an installer, but an already running process/application like an opened command prompt or PowerShell window was not closed/exited and opened/restarted after PATH modification. This is necessary as described in detail in chapter F) below.
6. An executable in %SystemRoot%\System32 is not found on 64-bit Windows.
There is the directory %SystemRoot%\System32 with 64-bit executables and %SystemRoot%\SysWOW64 with 32-bit executables on 64-bit Windows with a processor supporting also the x86 instruction set. Most executables exist in both directories. But there are some executables existing only in System32 and a few only in SysWOW64.
The system PATH contains by default as first folder path %SystemRoot%\System32. But which one of the two Windows system folders is searched for the executable specified without path or with the path %SystemRoot%\System32 depends on the execution environment. An application or script executed in 64-bit environment is really accessing %SystemRoot%\System32 while an application or script executed in 32-bit environment is redirected by the Windows file system redirector to the directory %SystemRoot%\SysWOW64.
An application or script running in 32-bit environment which wants to run a 64-bit executable in %SystemRoot%\System32 has to use the fully qualified file name of the executable with file path %SystemRoot%\Sysnative.
Note: %SystemRoot%\Sysnative is neither a directory nor any type of link. It is something very special existing only for x86 applications. It does not exist for amd64 applications. The condition if exist %SystemRoot%\Sysnative in a batch file is always false in both environments, but if exist %SystemRoot%\Sysnative\cmd.exe is true in 32-bit execution environment and false in 64-bit environment and also on 32-bit Windows. This condition can be used in batch scripts to find out if the batch file is processed by 32-bit cmd.exe in %SystemRoot%\SysWOW64 on 64-bit Windows which can be important to know depending on the task.
See also the Microsoft documentations WOW64 Implementation Details and Registry Keys Affected by WOW64.
7. PATH contains a reference to a not (yet) defined environment variable.
It is possible to specify in PATH a folder path using a reference to value of another environment variable like SystemRoot. It is important that this environment variable is also defined in same set of environment variables or a set of environment variables processed first by Windows.
For example if %JAVA_HOME%\bin is added to system PATH environment variable, there must be defined also a system environment variable JAVA_HOME with the base folder path to Java program files. It is not enough to have defined a user environment variable JAVA_HOME or define the environment variable JAVA_HOME later in the local environment of a batch file.
%JAVA_HOME%\bin added to user PATH is expanded by Windows to a full qualified folder path if the environment variable JAVA_HOME is defined either as system or as user environment variable, but not on JAVA_HOME defined later in the local environment of a Windows command process.
Such a mistake can be seen easily by opening a new command prompt window after making a modification on system or user PATH from Windows start menu and running set path. The output PATH should not contain anymore any %Variable% environment variable value reference.
8. The LOCAL variable PATH was modified before on command line or in batch file.
Run set path on command line or add this command to the batch file above the command line which fails to see the current values of the environment variables PATH and PATHEXT.
That reason is responsible for external command SORT not being found on execution of the batch file which contains somewhere above set path=....
9. LOCAL variable PATH is too long.
The local variable PATH of cmd.exe is too long. The Windows Command Processor fails to find any executable/script in the folder paths of local Path if the string value is longer than 8191 characters.
Please see my second answer here for more details regarding to length limitations of PATH.
Thanks goes to Albert Mosiałek for informing me about this cause of a not recognized program or script.
E) How to avoid this error message?
Best is coding a batch file for being independent on PATH and PATHEXT and the order of directories in PATH which means here using the command line:
FOR /f "delims=" %%d in ('dir /s /b /ad ^| %SystemRoot%\System32\sort.exe /r') do rd "%%d"
Any external command of which executable is stored in %SystemRoot%\System32 should be specified in a batch file with this path and with file extension .exe. Then Windows command interpreter does not need to search for a file using local PATH and PATHEXT and the batch file works always (as long as environment variable SystemRoot is not also modified in the batch file which I have never seen).
F) When is a system or user PATH change applied to processes?
When a user opens a command prompt window via Windows start menu or from within a Windows Explorer window, the user starts cmd.exe with implicit using option /K to keep the console window open after finishing a command which is good for debugging a batch file.
When a batch file is doubled clicked in Windows Explorer, the user starts cmd.exe for processing the batch file with implicit using option /C to close the console window after finishing batch processing which is not good for debugging a batch file as error messages cannot be seen in this case.
In both cases Windows creates a copy of the environment variables of the application starting cmd.exe which is usually Windows Explorer. Therefore the started command process has a local PATH of which value is the same as the parent process had on starting cmd.exe.
Example:
Open a command prompt window, run title Process1 and run set path.
Output is PATH and PATHEXT as currently defined for current user account in the console window having now the window title Process1.
Run set PATH=%SystemRoot%\System32 and next once again set path.
Output is again PATH and PATHEXT, but with PATH containing only one directory now.
Run start "Process2" and run in new console window with window title Process2 the command set path.
Output is PATH and PATHEXT with same values as before in Process1.
This demonstrates that on starting a new process the current environment variables of running process are copied and not what Windows itself has currently stored in Windows registry.
Run in Process2 the command set PATH= and next set path.
Output is only PATHEXT because local PATH does not exist anymore for Process2.
This demonstrates that every process can modify its environment variables including complete deletion.
Switch to Process1 window, run the command set PATH=%PATH%;%SystemRoot% and next set path.
Output is PATH with two directories and PATHEXT.
Run the command start "Process3" and in opened window with title Process3 the command set path.
Output is PATH with two directories as defined also for Process1 and PATHEXT.
Run in Process3 the command set PATH=%SystemRoot%\System32.
There are 3 command processes running with following values for local PATH when %SystemRoot% expands to C:\Windows:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
So what happens now on opening Control Panel – System – Advanced System Settings – Environment Variables and adding to list of User variables the new environment variable PATH with value C:\Temp, or in case of there is already a user PATH environment variable, edit PATH and append ;C:\Temp to the value?
Well, as long as the dialog window with title Environment Variables showing the two lists is opened, nothing happens on modifying the variables, until button OK is clicked to take over all changes into Windows registry and close the window.
Let's go back to the three running command processes and run in Process1, Process2 and Process3 the command set path. It can be seen:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
Nothing changed on already running processes.
No process can modify the environment variables of a different running process!
Open from Windows start menu one more command prompt window and run in fourth command process the command set path. It can be seen that local PATH of fourth command process has appended the directory C:\Temp now.
Then close all four command processes and delete the added user PATH respectively remove ;C:\Temp from user PATH if having appended this directory path before.
How is this possible if no process can modify the environment variables of an already running process?
How was the environment variables list of Windows Explorer instance running as Windows desktop modified on closing Environment Variables window with button OK?
The answer on those two questions was given by eryksun in his comment.
After writing the modifications on system and user variables into registry on clicking button OK of Environment Variables window, Windows sends the WM_SETTINGCHANGE message to all top-level windows to inform the running applications about changed system parameters.
It is up to the application if this event message is handled at all and how. Windows Explorer running as Windows desktop reads the environment variables from registry and updates its environment variables list accordingly. Other applications like Total Commander handle this message also and update their lists of environment variables too. But cmd.exe does not do that fortunately as this would be really problematic.
Is there any possibility to modify a system or user variable with notification via WM_SETTINGCHANGE from within a command prompt window or batch file?
It is possible to modify the registry value of an environment variable using reg add command. But this does not result in sending WM_SETTINGCHANGE message to all top-level windows. Such changes done with reg add or with regedit require a restart of Windows (or at least a log off and log on of current user) to be taken into account at all.
But there is also the command setx which is designed for modifying a system or user variable and which also sends the WM_SETTINGCHANGE message to all top-level windows after registry was updated according to specified arguments. Run setx /? in a command prompt window for details. But please take into account that setx does not modify the local environment variable of running command process. This must be done with using command set used in addition to setx.
G) How is environment variable PATHEXT handled by Windows?
The environment variable PATHEXT with the list of file extensions is handled by Windows different in comparison to environment variable PATH.
System PATHEXT and user PATHEXT are NOT concatenated to local PATHEXT.
A user PATHEXT replaces the system PATHEXT for all processes running under environment of the account having defined a user PATHEXT.
There is defined only a system PATHEXT environment variable by default.
H) Is it possible to disable file search in current directory?
Windows command processor searches by default in current directory if file name of a script file or executable is specified on command line or in a batch file without any path which means without a backslash \ (or a forward slash / thanks to auto-correction) in argument string.
But on Windows Vista and later Windows client versions and on Windows Server 2003 and later Windows server versions it is indeed possible to disable searching for a script/executable in current directory specified without at least relative path .\ by defining the environment variable NoDefaultCurrentDirectoryInExePath with any value as written by eryksun in his comment below and explained by Microsoft's documentation about function NeedCurrentDirectoryForExePathA.
See Removing the current working directory from the path for more details on usage of this environment variable.
I) How to modify system or user PATH?
The system and user PATH environment variables are modified by a user best using the Windows GUI dialog window Environment Variables. This dialog window can be opened as follows:
Click on the Windows Start menu button.
Type on keyboard environment variables.
There are offered by Windows the two items:
Edit the system environment variables
Edit environment variables for your account
Click on one of the two items to open the Environment Variables window.
There can be also opened the Windows Control Panel. There must be next clicked on System and Security with Category selected for display option View by. Next must be clicked System. There must be clicked on left side Advanced system settings and next on the button Environment Variables...
The System window can be opened also by pressing the key combination Windows logo key + Pause if the keyboard has the key Pause at all or at least in combination with the key Fn. See also the Microsoft documentation page Keyboard shortcuts in Windows.
The further user actions are self-explaining for editing either user Path in upper list on existing at all or system Path in lower list.

Most probably, you messed around with the PATH variable. Perhaps you are overwriting it somewhere else in your script. Since sort is an external command, opposed to all the others in your command line like for, dir, rd, which are cmd-internal commands, the PATH variable is needed to find the command. If PATH is not defined, external commands are searched in the current working directory only. There is also a PATHEXT variable that is needed to define standard file extensions for executables, like .com, .exe. So when sort appears in command prompt or in a batch file, the system searches the current working directory and all directories specified by the PATH variable for a file with the base name sort and one of the extensions specified by PATHEXT. The command sort is actually called sort.exe and is usually located in C:\Windows\System32.

In my case, I was so sure that I didn't mess with PATH. It was that I wasn't aware that path and PATH are the same. CMD is case insensitive.

This answer contains additional information to my first answer here regarding to length limitations of PATH.
There are not good coded executables/scripts which modify system or user PATH without checking first if the folder path to add is not already in string value of one of the two PATH environment variables as reported by Albert Mosiałek in a comment. Multiple executions of such a program results in local PATH string value of cmd.exe becomes longer and longer until reaching the PATH length limitations.
The maximum length of local PATH string value of cmd.exe depends on version of Windows and multiple string length limitations.
Length limitations of PATH on Windows Vista and Windows 7
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 4095 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 4095 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 4095 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 4095 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely independent on length of system PATH if the string value stored in Windows registry is longer than 4095 characters.
The user PATH is appended with an additional semicolon in expanded form to local PATH of cmd.exe on being in Windows registry not longer than 4095 characters even if the user PATH is in expanded form longer than 4095 characters because of environment variable references like %APPDATA%, %LOCALAPPDATA% or %USERPROFILE%.
The local PATH of cmd.exe can reach the maximum length of 8191 characters in worst case with a very long and perhaps already once or twice truncated system PATH and a user PATH not longer than 4095 characters in Windows registry, but longer than 4095 characters in expanded form.
The Windows Command Processor cmd.exe stops finding any executable on local PATH becomes too long, for example if the system PATH of 4095 characters in registry expands to a string with 4087 characters and is concatenated with a semicolon and a user Path stored in Windows registry with 4074 characters, but is expanded to a string value of length 4104 characters, resulting in a local Path with a total length of 8192 characters. There is not even found anymore any executable in %SystemRoot%\System32 on local PATH string value has a length of 8192 characters although the execution of set path outputs the local PATH with first directory path C:\Windows\System32.
There is the Command prompt (Cmd. exe) command-line string limitation which means that the environment variable name PATH plus equal sign = plus the variable string value plus the string terminating null byte must fit into a character array of 8192 characters. The string value of the local environment variable PATH as output on running set path in a command prompt window cannot be longer than 8186 characters for that reason although in memory the string value of local Path can be up to 8191 characters.
The internal command SET of cmd.exe does not output anymore a line-feed on running set path in a command prompt window if the local PATH has a string value of 8186 or more characters. In the console window is displayed for that reason in this case the environment variable PATHEXT with the equal sign and its string value appended to end of the string value of the environment variable PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4094 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value with more than 4094 characters although the environment variable is stored in registry and is perhaps even defined in local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 4094 characters. A user can delete characters from such a long string value and save the shortened string value. But a user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters. A user can edit for that reason a user or system environment variable PATH with a string value longer than 2047 characters only for removal of a directory path using the Environment Variables window of Control Panel, but not for changing characters of an existing directory path or adding one more directory path to the environment variable string which is longer than 2047 characters.
Recommendations for PATH lengths
The system as well as the user PATH as stored in Windows registry and in their expanded form should be never longer than 4094 characters on Windows Vista and Windows 7 and are best both shorter than 2048 characters to be editable in the Control Panel windows.
Length limitations of PATH on Windows XP
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 2047 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 2047 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 2047 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 2047 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely if the expanded system PATH concatenated with the expanded user PATH with an additionally inserted semicolon results in a string value longer than 2047 characters. The maximum length of the user PATH on Windows XP depends for that reason on current length of expanded system PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4095 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value of more than 4095 characters although the environment variable is stored in registry and is perhaps even defined truncated in the local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 2047 characters. A user can edit an even longer string value and save the string value, but the string value is always truncated to a maximum length of 2047 characters as displayed in edit field of the window. A user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters.
Recommendations for PATH lengths
The system PATH as stored in Windows registry and in its expanded form should be never longer than 2047 characters on Windows XP.
The user PATH in its expanded form should be short enough to be not ignored on concatenating it with the system PATH.

Related

Xcopy command not working after upgrading version of an application [duplicate]

I have a one-line snippet that works perfectly in the command line, but fails and throws up errors when I run it as part of a batch script.
The below commands behaves as expected, deleting all empty subfolders in the folder.
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"
However, when put in a batch file like so...
FOR /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"
...it throws the standard error:
Sort is not recognised as an internal or external command
I've been experimenting for the last hour or so with and without escaping the pipe, changing the order of the options, looking up the documentation of both dir and sort, etc., but I've still not been able to figure out what's going on here. The rest of the batch file, which is only a few lines, works fine, and this is the only line in it that fails.
A) How does Windows command processor search for commands?
Windows command processor searches for a COMMAND to execute which
is not an internal command of cmd.exe and
is just specified with file name without file extension and without path
for a file matching the pattern command.* and having a file extension listed in local environment variable PATHEXT
first in current directory and
next in all directories of local environment variable PATH.
SORT and FIND and FINDSTR and ROBOCOPY and XCOPY and many more commands are not internal commands of cmd.exe. They are console applications installed with Windows located in directory %SystemRoot%\System32 having the file name sort.exe, find.exe, findstr.exe, robocopy.exe, xcopy.exe, ...
Such console applications available by default on Windows are called external commands to distinguish them better from console applications not installed with Windows operating system.
B) How is the environment variable PATH defined?
There are three types of PATH variables:
System PATH which is used for all accounts and stored in Windows registry under key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
User PATH which is used only for current account and stored in Windows registry under key:
HKEY_CURRENT_USER\Environment
Local PATH which is always a copy of the local PATH of parent process which started the current process.
Windows concatenates system and user PATH to local PATH for the Windows Explorer instance used as Windows desktop with the shortcuts on the desktop screen and the Windows start menu and the Windows taskbar as visible interface for the user called Windows shell from which users usually start programs.
The entire currently active environment variables list of running process is copied for the new process by Windows on starting a new process. The Windows kernel library function CreateProcess does this environment variables list copy from the memory of the current process to the memory of the new process on function parameter lpEnvironment (long pointer to environment) being a null pointer. One of the CreateProcess functions is always used on Windows on starting an executable from another executable.
The parent process cannot modify the environment variables of any child process nor can a child process modify the environment variables of its parent process.
This means once a process like cmd.exe was started for execution of a batch file, the process has its own set of environment variables which only the process itself can modify. No other process can modify the environment variables of an already running process.
C) What does the error message mean?
The error message
'...' is not recognized as an internal or external command,operable program or batch file.
always means that
the file name of a
console application
GUI application
script (batch file, PowerShell script, Perl script, VBScript, JScript, ...)
was specified for execution most likely without file extension and without (complete) path to the executable/script file and
Windows failed to find a file matching the pattern FileName.* with a file extension listed in currently active environment variable PATHEXT in current directory or any other directory in currently active environment variable PATH.
D) What are the possible reasons for this error message?
Typical reasons are:
1. The file name of the file to execute was specified wrong due to a typing mistake.
Check character by character the name of the command/executable.
2. The current directory is different to the directory containing the file to execute.
Run echo Current directory is: %CD% on command line or add this line to the batch file above the command line which fails to see what the current directory is.
3. The executable or script to run is not installed at all.
Verify the existence of the executable to run. Some installation packages work only if other packages like Java, NPM, PHP, etc. were installed before.
4. The directory of the file to execute is not in PATH at all.
Open in Windows Control Panel the System settings window, click on Advanced system settings on left side, click on button Environment Variables and look in both lists for Path and their values. By default Path exists only in list of System variables.
5. A running process/application was not restarted after modification of system or user PATH.
A modification of system PATH or user PATH with command setx or via Control Panel – System and Security – System – Advanced system settings - Environment Variables was made by the user or an installer, but an already running process/application like an opened command prompt or PowerShell window was not closed/exited and opened/restarted after PATH modification. This is necessary as described in detail in chapter F) below.
6. An executable in %SystemRoot%\System32 is not found on 64-bit Windows.
There is the directory %SystemRoot%\System32 with 64-bit executables and %SystemRoot%\SysWOW64 with 32-bit executables on 64-bit Windows with a processor supporting also the x86 instruction set. Most executables exist in both directories. But there are some executables existing only in System32 and a few only in SysWOW64.
The system PATH contains by default as first folder path %SystemRoot%\System32. But which one of the two Windows system folders is searched for the executable specified without path or with the path %SystemRoot%\System32 depends on the execution environment. An application or script executed in 64-bit environment is really accessing %SystemRoot%\System32 while an application or script executed in 32-bit environment is redirected by the Windows file system redirector to the directory %SystemRoot%\SysWOW64.
An application or script running in 32-bit environment which wants to run a 64-bit executable in %SystemRoot%\System32 has to use the fully qualified file name of the executable with file path %SystemRoot%\Sysnative.
Note: %SystemRoot%\Sysnative is neither a directory nor any type of link. It is something very special existing only for x86 applications. It does not exist for amd64 applications. The condition if exist %SystemRoot%\Sysnative in a batch file is always false in both environments, but if exist %SystemRoot%\Sysnative\cmd.exe is true in 32-bit execution environment and false in 64-bit environment and also on 32-bit Windows. This condition can be used in batch scripts to find out if the batch file is processed by 32-bit cmd.exe in %SystemRoot%\SysWOW64 on 64-bit Windows which can be important to know depending on the task.
See also the Microsoft documentations WOW64 Implementation Details and Registry Keys Affected by WOW64.
7. PATH contains a reference to a not (yet) defined environment variable.
It is possible to specify in PATH a folder path using a reference to value of another environment variable like SystemRoot. It is important that this environment variable is also defined in same set of environment variables or a set of environment variables processed first by Windows.
For example if %JAVA_HOME%\bin is added to system PATH environment variable, there must be defined also a system environment variable JAVA_HOME with the base folder path to Java program files. It is not enough to have defined a user environment variable JAVA_HOME or define the environment variable JAVA_HOME later in the local environment of a batch file.
%JAVA_HOME%\bin added to user PATH is expanded by Windows to a full qualified folder path if the environment variable JAVA_HOME is defined either as system or as user environment variable, but not on JAVA_HOME defined later in the local environment of a Windows command process.
Such a mistake can be seen easily by opening a new command prompt window after making a modification on system or user PATH from Windows start menu and running set path. The output PATH should not contain anymore any %Variable% environment variable value reference.
8. The LOCAL variable PATH was modified before on command line or in batch file.
Run set path on command line or add this command to the batch file above the command line which fails to see the current values of the environment variables PATH and PATHEXT.
That reason is responsible for external command SORT not being found on execution of the batch file which contains somewhere above set path=....
9. LOCAL variable PATH is too long.
The local variable PATH of cmd.exe is too long. The Windows Command Processor fails to find any executable/script in the folder paths of local Path if the string value is longer than 8191 characters.
Please see my second answer here for more details regarding to length limitations of PATH.
Thanks goes to Albert Mosiałek for informing me about this cause of a not recognized program or script.
E) How to avoid this error message?
Best is coding a batch file for being independent on PATH and PATHEXT and the order of directories in PATH which means here using the command line:
FOR /f "delims=" %%d in ('dir /s /b /ad ^| %SystemRoot%\System32\sort.exe /r') do rd "%%d"
Any external command of which executable is stored in %SystemRoot%\System32 should be specified in a batch file with this path and with file extension .exe. Then Windows command interpreter does not need to search for a file using local PATH and PATHEXT and the batch file works always (as long as environment variable SystemRoot is not also modified in the batch file which I have never seen).
F) When is a system or user PATH change applied to processes?
When a user opens a command prompt window via Windows start menu or from within a Windows Explorer window, the user starts cmd.exe with implicit using option /K to keep the console window open after finishing a command which is good for debugging a batch file.
When a batch file is doubled clicked in Windows Explorer, the user starts cmd.exe for processing the batch file with implicit using option /C to close the console window after finishing batch processing which is not good for debugging a batch file as error messages cannot be seen in this case.
In both cases Windows creates a copy of the environment variables of the application starting cmd.exe which is usually Windows Explorer. Therefore the started command process has a local PATH of which value is the same as the parent process had on starting cmd.exe.
Example:
Open a command prompt window, run title Process1 and run set path.
Output is PATH and PATHEXT as currently defined for current user account in the console window having now the window title Process1.
Run set PATH=%SystemRoot%\System32 and next once again set path.
Output is again PATH and PATHEXT, but with PATH containing only one directory now.
Run start "Process2" and run in new console window with window title Process2 the command set path.
Output is PATH and PATHEXT with same values as before in Process1.
This demonstrates that on starting a new process the current environment variables of running process are copied and not what Windows itself has currently stored in Windows registry.
Run in Process2 the command set PATH= and next set path.
Output is only PATHEXT because local PATH does not exist anymore for Process2.
This demonstrates that every process can modify its environment variables including complete deletion.
Switch to Process1 window, run the command set PATH=%PATH%;%SystemRoot% and next set path.
Output is PATH with two directories and PATHEXT.
Run the command start "Process3" and in opened window with title Process3 the command set path.
Output is PATH with two directories as defined also for Process1 and PATHEXT.
Run in Process3 the command set PATH=%SystemRoot%\System32.
There are 3 command processes running with following values for local PATH when %SystemRoot% expands to C:\Windows:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
So what happens now on opening Control Panel – System – Advanced System Settings – Environment Variables and adding to list of User variables the new environment variable PATH with value C:\Temp, or in case of there is already a user PATH environment variable, edit PATH and append ;C:\Temp to the value?
Well, as long as the dialog window with title Environment Variables showing the two lists is opened, nothing happens on modifying the variables, until button OK is clicked to take over all changes into Windows registry and close the window.
Let's go back to the three running command processes and run in Process1, Process2 and Process3 the command set path. It can be seen:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
Nothing changed on already running processes.
No process can modify the environment variables of a different running process!
Open from Windows start menu one more command prompt window and run in fourth command process the command set path. It can be seen that local PATH of fourth command process has appended the directory C:\Temp now.
Then close all four command processes and delete the added user PATH respectively remove ;C:\Temp from user PATH if having appended this directory path before.
How is this possible if no process can modify the environment variables of an already running process?
How was the environment variables list of Windows Explorer instance running as Windows desktop modified on closing Environment Variables window with button OK?
The answer on those two questions was given by eryksun in his comment.
After writing the modifications on system and user variables into registry on clicking button OK of Environment Variables window, Windows sends the WM_SETTINGCHANGE message to all top-level windows to inform the running applications about changed system parameters.
It is up to the application if this event message is handled at all and how. Windows Explorer running as Windows desktop reads the environment variables from registry and updates its environment variables list accordingly. Other applications like Total Commander handle this message also and update their lists of environment variables too. But cmd.exe does not do that fortunately as this would be really problematic.
Is there any possibility to modify a system or user variable with notification via WM_SETTINGCHANGE from within a command prompt window or batch file?
It is possible to modify the registry value of an environment variable using reg add command. But this does not result in sending WM_SETTINGCHANGE message to all top-level windows. Such changes done with reg add or with regedit require a restart of Windows (or at least a log off and log on of current user) to be taken into account at all.
But there is also the command setx which is designed for modifying a system or user variable and which also sends the WM_SETTINGCHANGE message to all top-level windows after registry was updated according to specified arguments. Run setx /? in a command prompt window for details. But please take into account that setx does not modify the local environment variable of running command process. This must be done with using command set used in addition to setx.
G) How is environment variable PATHEXT handled by Windows?
The environment variable PATHEXT with the list of file extensions is handled by Windows different in comparison to environment variable PATH.
System PATHEXT and user PATHEXT are NOT concatenated to local PATHEXT.
A user PATHEXT replaces the system PATHEXT for all processes running under environment of the account having defined a user PATHEXT.
There is defined only a system PATHEXT environment variable by default.
H) Is it possible to disable file search in current directory?
Windows command processor searches by default in current directory if file name of a script file or executable is specified on command line or in a batch file without any path which means without a backslash \ (or a forward slash / thanks to auto-correction) in argument string.
But on Windows Vista and later Windows client versions and on Windows Server 2003 and later Windows server versions it is indeed possible to disable searching for a script/executable in current directory specified without at least relative path .\ by defining the environment variable NoDefaultCurrentDirectoryInExePath with any value as written by eryksun in his comment below and explained by Microsoft's documentation about function NeedCurrentDirectoryForExePathA.
See Removing the current working directory from the path for more details on usage of this environment variable.
I) How to modify system or user PATH?
The system and user PATH environment variables are modified by a user best using the Windows GUI dialog window Environment Variables. This dialog window can be opened as follows:
Click on the Windows Start menu button.
Type on keyboard environment variables.
There are offered by Windows the two items:
Edit the system environment variables
Edit environment variables for your account
Click on one of the two items to open the Environment Variables window.
There can be also opened the Windows Control Panel. There must be next clicked on System and Security with Category selected for display option View by. Next must be clicked System. There must be clicked on left side Advanced system settings and next on the button Environment Variables...
The System window can be opened also by pressing the key combination Windows logo key + Pause if the keyboard has the key Pause at all or at least in combination with the key Fn. See also the Microsoft documentation page Keyboard shortcuts in Windows.
The further user actions are self-explaining for editing either user Path in upper list on existing at all or system Path in lower list.
Most probably, you messed around with the PATH variable. Perhaps you are overwriting it somewhere else in your script. Since sort is an external command, opposed to all the others in your command line like for, dir, rd, which are cmd-internal commands, the PATH variable is needed to find the command. If PATH is not defined, external commands are searched in the current working directory only. There is also a PATHEXT variable that is needed to define standard file extensions for executables, like .com, .exe. So when sort appears in command prompt or in a batch file, the system searches the current working directory and all directories specified by the PATH variable for a file with the base name sort and one of the extensions specified by PATHEXT. The command sort is actually called sort.exe and is usually located in C:\Windows\System32.
In my case, I was so sure that I didn't mess with PATH. It was that I wasn't aware that path and PATH are the same. CMD is case insensitive.
This answer contains additional information to my first answer here regarding to length limitations of PATH.
There are not good coded executables/scripts which modify system or user PATH without checking first if the folder path to add is not already in string value of one of the two PATH environment variables as reported by Albert Mosiałek in a comment. Multiple executions of such a program results in local PATH string value of cmd.exe becomes longer and longer until reaching the PATH length limitations.
The maximum length of local PATH string value of cmd.exe depends on version of Windows and multiple string length limitations.
Length limitations of PATH on Windows Vista and Windows 7
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 4095 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 4095 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 4095 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 4095 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely independent on length of system PATH if the string value stored in Windows registry is longer than 4095 characters.
The user PATH is appended with an additional semicolon in expanded form to local PATH of cmd.exe on being in Windows registry not longer than 4095 characters even if the user PATH is in expanded form longer than 4095 characters because of environment variable references like %APPDATA%, %LOCALAPPDATA% or %USERPROFILE%.
The local PATH of cmd.exe can reach the maximum length of 8191 characters in worst case with a very long and perhaps already once or twice truncated system PATH and a user PATH not longer than 4095 characters in Windows registry, but longer than 4095 characters in expanded form.
The Windows Command Processor cmd.exe stops finding any executable on local PATH becomes too long, for example if the system PATH of 4095 characters in registry expands to a string with 4087 characters and is concatenated with a semicolon and a user Path stored in Windows registry with 4074 characters, but is expanded to a string value of length 4104 characters, resulting in a local Path with a total length of 8192 characters. There is not even found anymore any executable in %SystemRoot%\System32 on local PATH string value has a length of 8192 characters although the execution of set path outputs the local PATH with first directory path C:\Windows\System32.
There is the Command prompt (Cmd. exe) command-line string limitation which means that the environment variable name PATH plus equal sign = plus the variable string value plus the string terminating null byte must fit into a character array of 8192 characters. The string value of the local environment variable PATH as output on running set path in a command prompt window cannot be longer than 8186 characters for that reason although in memory the string value of local Path can be up to 8191 characters.
The internal command SET of cmd.exe does not output anymore a line-feed on running set path in a command prompt window if the local PATH has a string value of 8186 or more characters. In the console window is displayed for that reason in this case the environment variable PATHEXT with the equal sign and its string value appended to end of the string value of the environment variable PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4094 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value with more than 4094 characters although the environment variable is stored in registry and is perhaps even defined in local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 4094 characters. A user can delete characters from such a long string value and save the shortened string value. But a user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters. A user can edit for that reason a user or system environment variable PATH with a string value longer than 2047 characters only for removal of a directory path using the Environment Variables window of Control Panel, but not for changing characters of an existing directory path or adding one more directory path to the environment variable string which is longer than 2047 characters.
Recommendations for PATH lengths
The system as well as the user PATH as stored in Windows registry and in their expanded form should be never longer than 4094 characters on Windows Vista and Windows 7 and are best both shorter than 2048 characters to be editable in the Control Panel windows.
Length limitations of PATH on Windows XP
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 2047 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 2047 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 2047 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 2047 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely if the expanded system PATH concatenated with the expanded user PATH with an additionally inserted semicolon results in a string value longer than 2047 characters. The maximum length of the user PATH on Windows XP depends for that reason on current length of expanded system PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4095 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value of more than 4095 characters although the environment variable is stored in registry and is perhaps even defined truncated in the local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 2047 characters. A user can edit an even longer string value and save the string value, but the string value is always truncated to a maximum length of 2047 characters as displayed in edit field of the window. A user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters.
Recommendations for PATH lengths
The system PATH as stored in Windows registry and in its expanded form should be never longer than 2047 characters on Windows XP.
The user PATH in its expanded form should be short enough to be not ignored on concatenating it with the system PATH.

bat file behaviour differs when launched from cmdline or doubleclick [duplicate]

I have a one-line snippet that works perfectly in the command line, but fails and throws up errors when I run it as part of a batch script.
The below commands behaves as expected, deleting all empty subfolders in the folder.
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"
However, when put in a batch file like so...
FOR /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"
...it throws the standard error:
Sort is not recognised as an internal or external command
I've been experimenting for the last hour or so with and without escaping the pipe, changing the order of the options, looking up the documentation of both dir and sort, etc., but I've still not been able to figure out what's going on here. The rest of the batch file, which is only a few lines, works fine, and this is the only line in it that fails.
A) How does Windows command processor search for commands?
Windows command processor searches for a COMMAND to execute which
is not an internal command of cmd.exe and
is just specified with file name without file extension and without path
for a file matching the pattern command.* and having a file extension listed in local environment variable PATHEXT
first in current directory and
next in all directories of local environment variable PATH.
SORT and FIND and FINDSTR and ROBOCOPY and XCOPY and many more commands are not internal commands of cmd.exe. They are console applications installed with Windows located in directory %SystemRoot%\System32 having the file name sort.exe, find.exe, findstr.exe, robocopy.exe, xcopy.exe, ...
Such console applications available by default on Windows are called external commands to distinguish them better from console applications not installed with Windows operating system.
B) How is the environment variable PATH defined?
There are three types of PATH variables:
System PATH which is used for all accounts and stored in Windows registry under key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
User PATH which is used only for current account and stored in Windows registry under key:
HKEY_CURRENT_USER\Environment
Local PATH which is always a copy of the local PATH of parent process which started the current process.
Windows concatenates system and user PATH to local PATH for the Windows Explorer instance used as Windows desktop with the shortcuts on the desktop screen and the Windows start menu and the Windows taskbar as visible interface for the user called Windows shell from which users usually start programs.
The entire currently active environment variables list of running process is copied for the new process by Windows on starting a new process. The Windows kernel library function CreateProcess does this environment variables list copy from the memory of the current process to the memory of the new process on function parameter lpEnvironment (long pointer to environment) being a null pointer. One of the CreateProcess functions is always used on Windows on starting an executable from another executable.
The parent process cannot modify the environment variables of any child process nor can a child process modify the environment variables of its parent process.
This means once a process like cmd.exe was started for execution of a batch file, the process has its own set of environment variables which only the process itself can modify. No other process can modify the environment variables of an already running process.
C) What does the error message mean?
The error message
'...' is not recognized as an internal or external command,operable program or batch file.
always means that
the file name of a
console application
GUI application
script (batch file, PowerShell script, Perl script, VBScript, JScript, ...)
was specified for execution most likely without file extension and without (complete) path to the executable/script file and
Windows failed to find a file matching the pattern FileName.* with a file extension listed in currently active environment variable PATHEXT in current directory or any other directory in currently active environment variable PATH.
D) What are the possible reasons for this error message?
Typical reasons are:
1. The file name of the file to execute was specified wrong due to a typing mistake.
Check character by character the name of the command/executable.
2. The current directory is different to the directory containing the file to execute.
Run echo Current directory is: %CD% on command line or add this line to the batch file above the command line which fails to see what the current directory is.
3. The executable or script to run is not installed at all.
Verify the existence of the executable to run. Some installation packages work only if other packages like Java, NPM, PHP, etc. were installed before.
4. The directory of the file to execute is not in PATH at all.
Open in Windows Control Panel the System settings window, click on Advanced system settings on left side, click on button Environment Variables and look in both lists for Path and their values. By default Path exists only in list of System variables.
5. A running process/application was not restarted after modification of system or user PATH.
A modification of system PATH or user PATH with command setx or via Control Panel – System and Security – System – Advanced system settings - Environment Variables was made by the user or an installer, but an already running process/application like an opened command prompt or PowerShell window was not closed/exited and opened/restarted after PATH modification. This is necessary as described in detail in chapter F) below.
6. An executable in %SystemRoot%\System32 is not found on 64-bit Windows.
There is the directory %SystemRoot%\System32 with 64-bit executables and %SystemRoot%\SysWOW64 with 32-bit executables on 64-bit Windows with a processor supporting also the x86 instruction set. Most executables exist in both directories. But there are some executables existing only in System32 and a few only in SysWOW64.
The system PATH contains by default as first folder path %SystemRoot%\System32. But which one of the two Windows system folders is searched for the executable specified without path or with the path %SystemRoot%\System32 depends on the execution environment. An application or script executed in 64-bit environment is really accessing %SystemRoot%\System32 while an application or script executed in 32-bit environment is redirected by the Windows file system redirector to the directory %SystemRoot%\SysWOW64.
An application or script running in 32-bit environment which wants to run a 64-bit executable in %SystemRoot%\System32 has to use the fully qualified file name of the executable with file path %SystemRoot%\Sysnative.
Note: %SystemRoot%\Sysnative is neither a directory nor any type of link. It is something very special existing only for x86 applications. It does not exist for amd64 applications. The condition if exist %SystemRoot%\Sysnative in a batch file is always false in both environments, but if exist %SystemRoot%\Sysnative\cmd.exe is true in 32-bit execution environment and false in 64-bit environment and also on 32-bit Windows. This condition can be used in batch scripts to find out if the batch file is processed by 32-bit cmd.exe in %SystemRoot%\SysWOW64 on 64-bit Windows which can be important to know depending on the task.
See also the Microsoft documentations WOW64 Implementation Details and Registry Keys Affected by WOW64.
7. PATH contains a reference to a not (yet) defined environment variable.
It is possible to specify in PATH a folder path using a reference to value of another environment variable like SystemRoot. It is important that this environment variable is also defined in same set of environment variables or a set of environment variables processed first by Windows.
For example if %JAVA_HOME%\bin is added to system PATH environment variable, there must be defined also a system environment variable JAVA_HOME with the base folder path to Java program files. It is not enough to have defined a user environment variable JAVA_HOME or define the environment variable JAVA_HOME later in the local environment of a batch file.
%JAVA_HOME%\bin added to user PATH is expanded by Windows to a full qualified folder path if the environment variable JAVA_HOME is defined either as system or as user environment variable, but not on JAVA_HOME defined later in the local environment of a Windows command process.
Such a mistake can be seen easily by opening a new command prompt window after making a modification on system or user PATH from Windows start menu and running set path. The output PATH should not contain anymore any %Variable% environment variable value reference.
8. The LOCAL variable PATH was modified before on command line or in batch file.
Run set path on command line or add this command to the batch file above the command line which fails to see the current values of the environment variables PATH and PATHEXT.
That reason is responsible for external command SORT not being found on execution of the batch file which contains somewhere above set path=....
9. LOCAL variable PATH is too long.
The local variable PATH of cmd.exe is too long. The Windows Command Processor fails to find any executable/script in the folder paths of local Path if the string value is longer than 8191 characters.
Please see my second answer here for more details regarding to length limitations of PATH.
Thanks goes to Albert Mosiałek for informing me about this cause of a not recognized program or script.
E) How to avoid this error message?
Best is coding a batch file for being independent on PATH and PATHEXT and the order of directories in PATH which means here using the command line:
FOR /f "delims=" %%d in ('dir /s /b /ad ^| %SystemRoot%\System32\sort.exe /r') do rd "%%d"
Any external command of which executable is stored in %SystemRoot%\System32 should be specified in a batch file with this path and with file extension .exe. Then Windows command interpreter does not need to search for a file using local PATH and PATHEXT and the batch file works always (as long as environment variable SystemRoot is not also modified in the batch file which I have never seen).
F) When is a system or user PATH change applied to processes?
When a user opens a command prompt window via Windows start menu or from within a Windows Explorer window, the user starts cmd.exe with implicit using option /K to keep the console window open after finishing a command which is good for debugging a batch file.
When a batch file is doubled clicked in Windows Explorer, the user starts cmd.exe for processing the batch file with implicit using option /C to close the console window after finishing batch processing which is not good for debugging a batch file as error messages cannot be seen in this case.
In both cases Windows creates a copy of the environment variables of the application starting cmd.exe which is usually Windows Explorer. Therefore the started command process has a local PATH of which value is the same as the parent process had on starting cmd.exe.
Example:
Open a command prompt window, run title Process1 and run set path.
Output is PATH and PATHEXT as currently defined for current user account in the console window having now the window title Process1.
Run set PATH=%SystemRoot%\System32 and next once again set path.
Output is again PATH and PATHEXT, but with PATH containing only one directory now.
Run start "Process2" and run in new console window with window title Process2 the command set path.
Output is PATH and PATHEXT with same values as before in Process1.
This demonstrates that on starting a new process the current environment variables of running process are copied and not what Windows itself has currently stored in Windows registry.
Run in Process2 the command set PATH= and next set path.
Output is only PATHEXT because local PATH does not exist anymore for Process2.
This demonstrates that every process can modify its environment variables including complete deletion.
Switch to Process1 window, run the command set PATH=%PATH%;%SystemRoot% and next set path.
Output is PATH with two directories and PATHEXT.
Run the command start "Process3" and in opened window with title Process3 the command set path.
Output is PATH with two directories as defined also for Process1 and PATHEXT.
Run in Process3 the command set PATH=%SystemRoot%\System32.
There are 3 command processes running with following values for local PATH when %SystemRoot% expands to C:\Windows:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
So what happens now on opening Control Panel – System – Advanced System Settings – Environment Variables and adding to list of User variables the new environment variable PATH with value C:\Temp, or in case of there is already a user PATH environment variable, edit PATH and append ;C:\Temp to the value?
Well, as long as the dialog window with title Environment Variables showing the two lists is opened, nothing happens on modifying the variables, until button OK is clicked to take over all changes into Windows registry and close the window.
Let's go back to the three running command processes and run in Process1, Process2 and Process3 the command set path. It can be seen:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
Nothing changed on already running processes.
No process can modify the environment variables of a different running process!
Open from Windows start menu one more command prompt window and run in fourth command process the command set path. It can be seen that local PATH of fourth command process has appended the directory C:\Temp now.
Then close all four command processes and delete the added user PATH respectively remove ;C:\Temp from user PATH if having appended this directory path before.
How is this possible if no process can modify the environment variables of an already running process?
How was the environment variables list of Windows Explorer instance running as Windows desktop modified on closing Environment Variables window with button OK?
The answer on those two questions was given by eryksun in his comment.
After writing the modifications on system and user variables into registry on clicking button OK of Environment Variables window, Windows sends the WM_SETTINGCHANGE message to all top-level windows to inform the running applications about changed system parameters.
It is up to the application if this event message is handled at all and how. Windows Explorer running as Windows desktop reads the environment variables from registry and updates its environment variables list accordingly. Other applications like Total Commander handle this message also and update their lists of environment variables too. But cmd.exe does not do that fortunately as this would be really problematic.
Is there any possibility to modify a system or user variable with notification via WM_SETTINGCHANGE from within a command prompt window or batch file?
It is possible to modify the registry value of an environment variable using reg add command. But this does not result in sending WM_SETTINGCHANGE message to all top-level windows. Such changes done with reg add or with regedit require a restart of Windows (or at least a log off and log on of current user) to be taken into account at all.
But there is also the command setx which is designed for modifying a system or user variable and which also sends the WM_SETTINGCHANGE message to all top-level windows after registry was updated according to specified arguments. Run setx /? in a command prompt window for details. But please take into account that setx does not modify the local environment variable of running command process. This must be done with using command set used in addition to setx.
G) How is environment variable PATHEXT handled by Windows?
The environment variable PATHEXT with the list of file extensions is handled by Windows different in comparison to environment variable PATH.
System PATHEXT and user PATHEXT are NOT concatenated to local PATHEXT.
A user PATHEXT replaces the system PATHEXT for all processes running under environment of the account having defined a user PATHEXT.
There is defined only a system PATHEXT environment variable by default.
H) Is it possible to disable file search in current directory?
Windows command processor searches by default in current directory if file name of a script file or executable is specified on command line or in a batch file without any path which means without a backslash \ (or a forward slash / thanks to auto-correction) in argument string.
But on Windows Vista and later Windows client versions and on Windows Server 2003 and later Windows server versions it is indeed possible to disable searching for a script/executable in current directory specified without at least relative path .\ by defining the environment variable NoDefaultCurrentDirectoryInExePath with any value as written by eryksun in his comment below and explained by Microsoft's documentation about function NeedCurrentDirectoryForExePathA.
See Removing the current working directory from the path for more details on usage of this environment variable.
I) How to modify system or user PATH?
The system and user PATH environment variables are modified by a user best using the Windows GUI dialog window Environment Variables. This dialog window can be opened as follows:
Click on the Windows Start menu button.
Type on keyboard environment variables.
There are offered by Windows the two items:
Edit the system environment variables
Edit environment variables for your account
Click on one of the two items to open the Environment Variables window.
There can be also opened the Windows Control Panel. There must be next clicked on System and Security with Category selected for display option View by. Next must be clicked System. There must be clicked on left side Advanced system settings and next on the button Environment Variables...
The System window can be opened also by pressing the key combination Windows logo key + Pause if the keyboard has the key Pause at all or at least in combination with the key Fn. See also the Microsoft documentation page Keyboard shortcuts in Windows.
The further user actions are self-explaining for editing either user Path in upper list on existing at all or system Path in lower list.
Most probably, you messed around with the PATH variable. Perhaps you are overwriting it somewhere else in your script. Since sort is an external command, opposed to all the others in your command line like for, dir, rd, which are cmd-internal commands, the PATH variable is needed to find the command. If PATH is not defined, external commands are searched in the current working directory only. There is also a PATHEXT variable that is needed to define standard file extensions for executables, like .com, .exe. So when sort appears in command prompt or in a batch file, the system searches the current working directory and all directories specified by the PATH variable for a file with the base name sort and one of the extensions specified by PATHEXT. The command sort is actually called sort.exe and is usually located in C:\Windows\System32.
In my case, I was so sure that I didn't mess with PATH. It was that I wasn't aware that path and PATH are the same. CMD is case insensitive.
This answer contains additional information to my first answer here regarding to length limitations of PATH.
There are not good coded executables/scripts which modify system or user PATH without checking first if the folder path to add is not already in string value of one of the two PATH environment variables as reported by Albert Mosiałek in a comment. Multiple executions of such a program results in local PATH string value of cmd.exe becomes longer and longer until reaching the PATH length limitations.
The maximum length of local PATH string value of cmd.exe depends on version of Windows and multiple string length limitations.
Length limitations of PATH on Windows Vista and Windows 7
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 4095 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 4095 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 4095 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 4095 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely independent on length of system PATH if the string value stored in Windows registry is longer than 4095 characters.
The user PATH is appended with an additional semicolon in expanded form to local PATH of cmd.exe on being in Windows registry not longer than 4095 characters even if the user PATH is in expanded form longer than 4095 characters because of environment variable references like %APPDATA%, %LOCALAPPDATA% or %USERPROFILE%.
The local PATH of cmd.exe can reach the maximum length of 8191 characters in worst case with a very long and perhaps already once or twice truncated system PATH and a user PATH not longer than 4095 characters in Windows registry, but longer than 4095 characters in expanded form.
The Windows Command Processor cmd.exe stops finding any executable on local PATH becomes too long, for example if the system PATH of 4095 characters in registry expands to a string with 4087 characters and is concatenated with a semicolon and a user Path stored in Windows registry with 4074 characters, but is expanded to a string value of length 4104 characters, resulting in a local Path with a total length of 8192 characters. There is not even found anymore any executable in %SystemRoot%\System32 on local PATH string value has a length of 8192 characters although the execution of set path outputs the local PATH with first directory path C:\Windows\System32.
There is the Command prompt (Cmd. exe) command-line string limitation which means that the environment variable name PATH plus equal sign = plus the variable string value plus the string terminating null byte must fit into a character array of 8192 characters. The string value of the local environment variable PATH as output on running set path in a command prompt window cannot be longer than 8186 characters for that reason although in memory the string value of local Path can be up to 8191 characters.
The internal command SET of cmd.exe does not output anymore a line-feed on running set path in a command prompt window if the local PATH has a string value of 8186 or more characters. In the console window is displayed for that reason in this case the environment variable PATHEXT with the equal sign and its string value appended to end of the string value of the environment variable PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4094 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value with more than 4094 characters although the environment variable is stored in registry and is perhaps even defined in local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 4094 characters. A user can delete characters from such a long string value and save the shortened string value. But a user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters. A user can edit for that reason a user or system environment variable PATH with a string value longer than 2047 characters only for removal of a directory path using the Environment Variables window of Control Panel, but not for changing characters of an existing directory path or adding one more directory path to the environment variable string which is longer than 2047 characters.
Recommendations for PATH lengths
The system as well as the user PATH as stored in Windows registry and in their expanded form should be never longer than 4094 characters on Windows Vista and Windows 7 and are best both shorter than 2048 characters to be editable in the Control Panel windows.
Length limitations of PATH on Windows XP
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 2047 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 2047 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 2047 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 2047 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely if the expanded system PATH concatenated with the expanded user PATH with an additionally inserted semicolon results in a string value longer than 2047 characters. The maximum length of the user PATH on Windows XP depends for that reason on current length of expanded system PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4095 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value of more than 4095 characters although the environment variable is stored in registry and is perhaps even defined truncated in the local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 2047 characters. A user can edit an even longer string value and save the string value, but the string value is always truncated to a maximum length of 2047 characters as displayed in edit field of the window. A user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters.
Recommendations for PATH lengths
The system PATH as stored in Windows registry and in its expanded form should be never longer than 2047 characters on Windows XP.
The user PATH in its expanded form should be short enough to be not ignored on concatenating it with the system PATH.

What is the reason for "X is not recognized as an internal or external command, operable program or batch file"?

I have a one-line snippet that works perfectly in the command line, but fails and throws up errors when I run it as part of a batch script.
The below commands behaves as expected, deleting all empty subfolders in the folder.
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"
However, when put in a batch file like so...
FOR /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"
...it throws the standard error:
Sort is not recognised as an internal or external command
I've been experimenting for the last hour or so with and without escaping the pipe, changing the order of the options, looking up the documentation of both dir and sort, etc., but I've still not been able to figure out what's going on here. The rest of the batch file, which is only a few lines, works fine, and this is the only line in it that fails.
A) How does Windows command processor search for commands?
Windows command processor searches for a COMMAND to execute which
is not an internal command of cmd.exe and
is just specified with file name without file extension and without path
for a file matching the pattern command.* and having a file extension listed in local environment variable PATHEXT
first in current directory and
next in all directories of local environment variable PATH.
SORT and FIND and FINDSTR and ROBOCOPY and XCOPY and many more commands are not internal commands of cmd.exe. They are console applications installed with Windows located in directory %SystemRoot%\System32 having the file name sort.exe, find.exe, findstr.exe, robocopy.exe, xcopy.exe, ...
Such console applications available by default on Windows are called external commands to distinguish them better from console applications not installed with Windows operating system.
B) How is the environment variable PATH defined?
There are three types of PATH variables:
System PATH which is used for all accounts and stored in Windows registry under key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
User PATH which is used only for current account and stored in Windows registry under key:
HKEY_CURRENT_USER\Environment
Local PATH which is always a copy of the local PATH of parent process which started the current process.
Windows concatenates system and user PATH to local PATH for the Windows Explorer instance used as Windows desktop with the shortcuts on the desktop screen and the Windows start menu and the Windows taskbar as visible interface for the user called Windows shell from which users usually start programs.
The entire currently active environment variables list of running process is copied for the new process by Windows on starting a new process. The Windows kernel library function CreateProcess does this environment variables list copy from the memory of the current process to the memory of the new process on function parameter lpEnvironment (long pointer to environment) being a null pointer. One of the CreateProcess functions is always used on Windows on starting an executable from another executable.
The parent process cannot modify the environment variables of any child process nor can a child process modify the environment variables of its parent process.
This means once a process like cmd.exe was started for execution of a batch file, the process has its own set of environment variables which only the process itself can modify. No other process can modify the environment variables of an already running process.
C) What does the error message mean?
The error message
'...' is not recognized as an internal or external command,operable program or batch file.
always means that
the file name of a
console application
GUI application
script (batch file, PowerShell script, Perl script, VBScript, JScript, ...)
was specified for execution most likely without file extension and without (complete) path to the executable/script file and
Windows failed to find a file matching the pattern FileName.* with a file extension listed in currently active environment variable PATHEXT in current directory or any other directory in currently active environment variable PATH.
D) What are the possible reasons for this error message?
Typical reasons are:
1. The file name of the file to execute was specified wrong due to a typing mistake.
Check character by character the name of the command/executable.
2. The current directory is different to the directory containing the file to execute.
Run echo Current directory is: %CD% on command line or add this line to the batch file above the command line which fails to see what the current directory is.
3. The executable or script to run is not installed at all.
Verify the existence of the executable to run. Some installation packages work only if other packages like Java, NPM, PHP, etc. were installed before.
4. The directory of the file to execute is not in PATH at all.
Open in Windows Control Panel the System settings window, click on Advanced system settings on left side, click on button Environment Variables and look in both lists for Path and their values. By default Path exists only in list of System variables.
5. A running process/application was not restarted after modification of system or user PATH.
A modification of system PATH or user PATH with command setx or via Control Panel – System and Security – System – Advanced system settings - Environment Variables was made by the user or an installer, but an already running process/application like an opened command prompt or PowerShell window was not closed/exited and opened/restarted after PATH modification. This is necessary as described in detail in chapter F) below.
6. An executable in %SystemRoot%\System32 is not found on 64-bit Windows.
There is the directory %SystemRoot%\System32 with 64-bit executables and %SystemRoot%\SysWOW64 with 32-bit executables on 64-bit Windows with a processor supporting also the x86 instruction set. Most executables exist in both directories. But there are some executables existing only in System32 and a few only in SysWOW64.
The system PATH contains by default as first folder path %SystemRoot%\System32. But which one of the two Windows system folders is searched for the executable specified without path or with the path %SystemRoot%\System32 depends on the execution environment. An application or script executed in 64-bit environment is really accessing %SystemRoot%\System32 while an application or script executed in 32-bit environment is redirected by the Windows file system redirector to the directory %SystemRoot%\SysWOW64.
An application or script running in 32-bit environment which wants to run a 64-bit executable in %SystemRoot%\System32 has to use the fully qualified file name of the executable with file path %SystemRoot%\Sysnative.
Note: %SystemRoot%\Sysnative is neither a directory nor any type of link. It is something very special existing only for x86 applications. It does not exist for amd64 applications. The condition if exist %SystemRoot%\Sysnative in a batch file is always false in both environments, but if exist %SystemRoot%\Sysnative\cmd.exe is true in 32-bit execution environment and false in 64-bit environment and also on 32-bit Windows. This condition can be used in batch scripts to find out if the batch file is processed by 32-bit cmd.exe in %SystemRoot%\SysWOW64 on 64-bit Windows which can be important to know depending on the task.
See also the Microsoft documentations WOW64 Implementation Details and Registry Keys Affected by WOW64.
7. PATH contains a reference to a not (yet) defined environment variable.
It is possible to specify in PATH a folder path using a reference to value of another environment variable like SystemRoot. It is important that this environment variable is also defined in same set of environment variables or a set of environment variables processed first by Windows.
For example if %JAVA_HOME%\bin is added to system PATH environment variable, there must be defined also a system environment variable JAVA_HOME with the base folder path to Java program files. It is not enough to have defined a user environment variable JAVA_HOME or define the environment variable JAVA_HOME later in the local environment of a batch file.
%JAVA_HOME%\bin added to user PATH is expanded by Windows to a full qualified folder path if the environment variable JAVA_HOME is defined either as system or as user environment variable, but not on JAVA_HOME defined later in the local environment of a Windows command process.
Such a mistake can be seen easily by opening a new command prompt window after making a modification on system or user PATH from Windows start menu and running set path. The output PATH should not contain anymore any %Variable% environment variable value reference.
8. The LOCAL variable PATH was modified before on command line or in batch file.
Run set path on command line or add this command to the batch file above the command line which fails to see the current values of the environment variables PATH and PATHEXT.
That reason is responsible for external command SORT not being found on execution of the batch file which contains somewhere above set path=....
9. LOCAL variable PATH is too long.
The local variable PATH of cmd.exe is too long. The Windows Command Processor fails to find any executable/script in the folder paths of local Path if the string value is longer than 8191 characters.
Please see my second answer here for more details regarding to length limitations of PATH.
Thanks goes to Albert Mosiałek for informing me about this cause of a not recognized program or script.
E) How to avoid this error message?
Best is coding a batch file for being independent on PATH and PATHEXT and the order of directories in PATH which means here using the command line:
FOR /f "delims=" %%d in ('dir /s /b /ad ^| %SystemRoot%\System32\sort.exe /r') do rd "%%d"
Any external command of which executable is stored in %SystemRoot%\System32 should be specified in a batch file with this path and with file extension .exe. Then Windows command interpreter does not need to search for a file using local PATH and PATHEXT and the batch file works always (as long as environment variable SystemRoot is not also modified in the batch file which I have never seen).
F) When is a system or user PATH change applied to processes?
When a user opens a command prompt window via Windows start menu or from within a Windows Explorer window, the user starts cmd.exe with implicit using option /K to keep the console window open after finishing a command which is good for debugging a batch file.
When a batch file is doubled clicked in Windows Explorer, the user starts cmd.exe for processing the batch file with implicit using option /C to close the console window after finishing batch processing which is not good for debugging a batch file as error messages cannot be seen in this case.
In both cases Windows creates a copy of the environment variables of the application starting cmd.exe which is usually Windows Explorer. Therefore the started command process has a local PATH of which value is the same as the parent process had on starting cmd.exe.
Example:
Open a command prompt window, run title Process1 and run set path.
Output is PATH and PATHEXT as currently defined for current user account in the console window having now the window title Process1.
Run set PATH=%SystemRoot%\System32 and next once again set path.
Output is again PATH and PATHEXT, but with PATH containing only one directory now.
Run start "Process2" and run in new console window with window title Process2 the command set path.
Output is PATH and PATHEXT with same values as before in Process1.
This demonstrates that on starting a new process the current environment variables of running process are copied and not what Windows itself has currently stored in Windows registry.
Run in Process2 the command set PATH= and next set path.
Output is only PATHEXT because local PATH does not exist anymore for Process2.
This demonstrates that every process can modify its environment variables including complete deletion.
Switch to Process1 window, run the command set PATH=%PATH%;%SystemRoot% and next set path.
Output is PATH with two directories and PATHEXT.
Run the command start "Process3" and in opened window with title Process3 the command set path.
Output is PATH with two directories as defined also for Process1 and PATHEXT.
Run in Process3 the command set PATH=%SystemRoot%\System32.
There are 3 command processes running with following values for local PATH when %SystemRoot% expands to C:\Windows:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
So what happens now on opening Control Panel – System – Advanced System Settings – Environment Variables and adding to list of User variables the new environment variable PATH with value C:\Temp, or in case of there is already a user PATH environment variable, edit PATH and append ;C:\Temp to the value?
Well, as long as the dialog window with title Environment Variables showing the two lists is opened, nothing happens on modifying the variables, until button OK is clicked to take over all changes into Windows registry and close the window.
Let's go back to the three running command processes and run in Process1, Process2 and Process3 the command set path. It can be seen:
Process1: PATH=C:\Windows\System32;C:\Windows
Process2: PATH does not exist at all.
Process3: PATH=C:\Windows\System32
Nothing changed on already running processes.
No process can modify the environment variables of a different running process!
Open from Windows start menu one more command prompt window and run in fourth command process the command set path. It can be seen that local PATH of fourth command process has appended the directory C:\Temp now.
Then close all four command processes and delete the added user PATH respectively remove ;C:\Temp from user PATH if having appended this directory path before.
How is this possible if no process can modify the environment variables of an already running process?
How was the environment variables list of Windows Explorer instance running as Windows desktop modified on closing Environment Variables window with button OK?
The answer on those two questions was given by eryksun in his comment.
After writing the modifications on system and user variables into registry on clicking button OK of Environment Variables window, Windows sends the WM_SETTINGCHANGE message to all top-level windows to inform the running applications about changed system parameters.
It is up to the application if this event message is handled at all and how. Windows Explorer running as Windows desktop reads the environment variables from registry and updates its environment variables list accordingly. Other applications like Total Commander handle this message also and update their lists of environment variables too. But cmd.exe does not do that fortunately as this would be really problematic.
Is there any possibility to modify a system or user variable with notification via WM_SETTINGCHANGE from within a command prompt window or batch file?
It is possible to modify the registry value of an environment variable using reg add command. But this does not result in sending WM_SETTINGCHANGE message to all top-level windows. Such changes done with reg add or with regedit require a restart of Windows (or at least a log off and log on of current user) to be taken into account at all.
But there is also the command setx which is designed for modifying a system or user variable and which also sends the WM_SETTINGCHANGE message to all top-level windows after registry was updated according to specified arguments. Run setx /? in a command prompt window for details. But please take into account that setx does not modify the local environment variable of running command process. This must be done with using command set used in addition to setx.
G) How is environment variable PATHEXT handled by Windows?
The environment variable PATHEXT with the list of file extensions is handled by Windows different in comparison to environment variable PATH.
System PATHEXT and user PATHEXT are NOT concatenated to local PATHEXT.
A user PATHEXT replaces the system PATHEXT for all processes running under environment of the account having defined a user PATHEXT.
There is defined only a system PATHEXT environment variable by default.
H) Is it possible to disable file search in current directory?
Windows command processor searches by default in current directory if file name of a script file or executable is specified on command line or in a batch file without any path which means without a backslash \ (or a forward slash / thanks to auto-correction) in argument string.
But on Windows Vista and later Windows client versions and on Windows Server 2003 and later Windows server versions it is indeed possible to disable searching for a script/executable in current directory specified without at least relative path .\ by defining the environment variable NoDefaultCurrentDirectoryInExePath with any value as written by eryksun in his comment below and explained by Microsoft's documentation about function NeedCurrentDirectoryForExePathA.
See Removing the current working directory from the path for more details on usage of this environment variable.
I) How to modify system or user PATH?
The system and user PATH environment variables are modified by a user best using the Windows GUI dialog window Environment Variables. This dialog window can be opened as follows:
Click on the Windows Start menu button.
Type on keyboard environment variables.
There are offered by Windows the two items:
Edit the system environment variables
Edit environment variables for your account
Click on one of the two items to open the Environment Variables window.
There can be also opened the Windows Control Panel. There must be next clicked on System and Security with Category selected for display option View by. Next must be clicked System. There must be clicked on left side Advanced system settings and next on the button Environment Variables...
The System window can be opened also by pressing the key combination Windows logo key + Pause if the keyboard has the key Pause at all or at least in combination with the key Fn. See also the Microsoft documentation page Keyboard shortcuts in Windows.
The further user actions are self-explaining for editing either user Path in upper list on existing at all or system Path in lower list.
Most probably, you messed around with the PATH variable. Perhaps you are overwriting it somewhere else in your script. Since sort is an external command, opposed to all the others in your command line like for, dir, rd, which are cmd-internal commands, the PATH variable is needed to find the command. If PATH is not defined, external commands are searched in the current working directory only. There is also a PATHEXT variable that is needed to define standard file extensions for executables, like .com, .exe. So when sort appears in command prompt or in a batch file, the system searches the current working directory and all directories specified by the PATH variable for a file with the base name sort and one of the extensions specified by PATHEXT. The command sort is actually called sort.exe and is usually located in C:\Windows\System32.
In my case, I was so sure that I didn't mess with PATH. It was that I wasn't aware that path and PATH are the same. CMD is case insensitive.
This answer contains additional information to my first answer here regarding to length limitations of PATH.
There are not good coded executables/scripts which modify system or user PATH without checking first if the folder path to add is not already in string value of one of the two PATH environment variables as reported by Albert Mosiałek in a comment. Multiple executions of such a program results in local PATH string value of cmd.exe becomes longer and longer until reaching the PATH length limitations.
The maximum length of local PATH string value of cmd.exe depends on version of Windows and multiple string length limitations.
Length limitations of PATH on Windows Vista and Windows 7
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 4095 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 4095 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 4095 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 4095 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely independent on length of system PATH if the string value stored in Windows registry is longer than 4095 characters.
The user PATH is appended with an additional semicolon in expanded form to local PATH of cmd.exe on being in Windows registry not longer than 4095 characters even if the user PATH is in expanded form longer than 4095 characters because of environment variable references like %APPDATA%, %LOCALAPPDATA% or %USERPROFILE%.
The local PATH of cmd.exe can reach the maximum length of 8191 characters in worst case with a very long and perhaps already once or twice truncated system PATH and a user PATH not longer than 4095 characters in Windows registry, but longer than 4095 characters in expanded form.
The Windows Command Processor cmd.exe stops finding any executable on local PATH becomes too long, for example if the system PATH of 4095 characters in registry expands to a string with 4087 characters and is concatenated with a semicolon and a user Path stored in Windows registry with 4074 characters, but is expanded to a string value of length 4104 characters, resulting in a local Path with a total length of 8192 characters. There is not even found anymore any executable in %SystemRoot%\System32 on local PATH string value has a length of 8192 characters although the execution of set path outputs the local PATH with first directory path C:\Windows\System32.
There is the Command prompt (Cmd. exe) command-line string limitation which means that the environment variable name PATH plus equal sign = plus the variable string value plus the string terminating null byte must fit into a character array of 8192 characters. The string value of the local environment variable PATH as output on running set path in a command prompt window cannot be longer than 8186 characters for that reason although in memory the string value of local Path can be up to 8191 characters.
The internal command SET of cmd.exe does not output anymore a line-feed on running set path in a command prompt window if the local PATH has a string value of 8186 or more characters. In the console window is displayed for that reason in this case the environment variable PATHEXT with the equal sign and its string value appended to end of the string value of the environment variable PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4094 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value with more than 4094 characters although the environment variable is stored in registry and is perhaps even defined in local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 4094 characters. A user can delete characters from such a long string value and save the shortened string value. But a user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters. A user can edit for that reason a user or system environment variable PATH with a string value longer than 2047 characters only for removal of a directory path using the Environment Variables window of Control Panel, but not for changing characters of an existing directory path or adding one more directory path to the environment variable string which is longer than 2047 characters.
Recommendations for PATH lengths
The system as well as the user PATH as stored in Windows registry and in their expanded form should be never longer than 4094 characters on Windows Vista and Windows 7 and are best both shorter than 2048 characters to be editable in the Control Panel windows.
Length limitations of PATH on Windows XP
Length limitations of system PATH
The system PATH as stored in Windows registry is truncated to its maximum length of 2047 characters before expanding all the environment variable references. The truncated string assigned to local PATH of cmd.exe can be also shorter than 2047 characters on system PATH contains environment variable references like %SystemRoot% (12 characters) expanding to C:\Windows (10 characters) and no user PATH is stored in Windows registry.
The system PATH is truncated to its maximum length of 2047 characters after expansion of the environment variable references. The truncated string assigned to local PATH of cmd.exe can be longer than the string value stored in Windows registry if environment variable references expand to strings which are longer than the environment variable reference strings.
In worst case the system PATH is truncated twice to a maximum length of 2047 characters, the first time before and the second time after expansion of the environment variable references.
Length limitations of user PATH
The user PATH is ignored completely if the expanded system PATH concatenated with the expanded user PATH with an additionally inserted semicolon results in a string value longer than 2047 characters. The maximum length of the user PATH on Windows XP depends for that reason on current length of expanded system PATH.
Length limitations of Control Panel windows for editing environment variables
A user or system PATH or any other in Windows registry persistent stored environment variable with a string value longer than 4095 characters is not displayed in the Environment Variables dialog window. For a user it looks like the environment variable does not exist which has a string value of more than 4095 characters although the environment variable is stored in registry and is perhaps even defined truncated in the local environment of running processes. The other user and system variables are still displayed in the Environment Variables window.
The Edit User Variable and Edit System Variable dialog windows display a Variable value with up to 2047 characters. A user can edit an even longer string value and save the string value, but the string value is always truncated to a maximum length of 2047 characters as displayed in edit field of the window. A user cannot append characters or replace existing characters on string value of the environment variable is longer than 2047 characters.
Recommendations for PATH lengths
The system PATH as stored in Windows registry and in its expanded form should be never longer than 2047 characters on Windows XP.
The user PATH in its expanded form should be short enough to be not ignored on concatenating it with the system PATH.

System versus user PATH environmental variable...winmerge works only if I add the path to the user PATH

If I add C:\Program Files (x86)\WinMerge to the User PATH variable(by right click on computer -> advanced system settings -> environmental variables), once I open a new cmd shell WinmergeU.exe is not recognized. If I add that path to the System PATH variable, WinmergeU.exe is correctly recognized instead. I though there was no difference between User and System, beside the fact that if I set it on System all the users will see it, while the User PATH is local. Am I doing something wrong?
EDIT 1:
In the follow you can see first the case in which C:\Program Files (x86)\WinMerge is added to the System PATH variable (but not to the User), then when it is added to the User PATH variable (but not to the System). In the first case Winmerge window launch correctly (not shown) and as you can see the path is shown by the echo %PATH% command. In the second case it does not launch and the path it is not shown by echo %PATH%. (note that I clearly confirmed with OK and closed the environmental variable windows before taking these screenshots, and I opened a new cmd right after changing PATH and pressing ok). This issue might be related to my question here (Does echo %PATH% expand to only the system or also the user variables?) but since it might not be I posted two different question.
You must be getting something wrong, or have environmental problems with your machine. Adding a user PATH environment variable does result in it being merged into the environment of a new process.
Update: Perhaps this comment from the MSDN topic on environment variables might be pertinent:
Found out that on Windows Server 2003, once the system PATH passes 1920 characters, the user PATH environment variable is no longer merged with it to set the process PATH environment variable, even though the full system PATH (even if larger) will be included in the process PATH variable.
On Windows 7, also make sure that the system path does not end with a backslash. If it does, the USER PATH is appended to the system path as per usual, but after a line break, which breaks things. In the latter case, the simple command "path" and "echo %PATH% " will print 2 different outputs.
For 16.6, I've confirmed this issue to be a path length issue as well. At a cmd prompt, typing 'set', you can see all of the env. variables. The user path cadence variables and others weren't included. I saved the original complete path text, then I went through and trimmed specific (system) path elements that were deemed unnecessary. after this, in a new cmd session, typing 'set' now shows the user path elements tacked on to the end of the system path elements, because they now fit.

Adding a directory to the PATH environment variable in Windows

I am trying to add C:\xampp\php 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:\xampp\php directory:
PATH=D:\Program Files\Autodesk\Maya2008\bin;C:\Ruby192\bin;C:\WINDOWS\system32;C:\WINDOWS;
C:\WINDOWS\System32\Wbem;C:\PROGRA~1\DISKEE~2\DISKEE~1\;c:\Program Files\Microsoft SQL
Server\90\Tools\binn\;C:\Program Files\QuickTime\QTSystem\;D:\Program Files\TortoiseSVN\bin
;D:\Program Files\Bazaar;C:\Program Files\Android\android-sdk\tools;D:\Program Files\
Microsoft Visual Studio\Common\Tools\WinNT;D:\Program Files\Microsoft Visual Studio\Common
\MSDev98\Bin;D:\Program Files\Microsoft Visual Studio\Common\Tools;D:\Program Files\
Microsoft Visual Studio\VC98\bin
I have two questions:
Why did this happen? Is there something I did wrong?
Also, how do I add directories to my PATH variable using the console (and programmatically, with a batch file)?
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:\your\path\here\
This command appends C:\your\path\here\ 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:\your\path\here\ – The %PATH% part expands to the current value of PATH, and ;C:\your\path\here\ is then concatenated to it. This becomes the new PATH.
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:\your\path\here\"
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.
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.
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:\xampp\php
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%
I would use PowerShell instead!
To add a directory to PATH using PowerShell, do the following:
$PATH = [Environment]::GetEnvironmentVariable("PATH")
$xampp_path = "C:\xampp\php"
[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:\xampp\php 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:\xampp\php"
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.
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
Backup your PATH - SETX will truncate your junk longer than 1024 characters
Don't call SETX %PATH%;xxx - adds the system path into the user path
Don't call SETX %PATH%;xxx /M - adds the user path into the system path
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:
HKCU\Environment
System Variables:
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
Usage instructions
Append to User PATH
append_user_path.cmd
#ECHO OFF
REM usage: append_user_path "path"
SET Key="HKCU\Environment"
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="HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
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%tex\texmf-mswin\bin\context.exe" set PLATFORM=mswin
if exist "%OWNPATH%tex\texmf-win64\bin\context.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="HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
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%tex\texmf-%PLATFORM%\bin
rem Persist the PATH environment variable
setx PATH "%%B;%OWNPATH%tex\texmf-%PLATFORM%\bin" /M
)
)
)
1. Not strictly true
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.
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!
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:\xampp\php;%PATH%;
Use pathed from gtools.
It does things in an intuitive way. For example:
pathed /REMOVE "c:\my\folder"
pathed /APPEND "c:\my\folder"
It shows results without the need to spawn a new cmd!
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
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:\path\to\where\the\command\resides"
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.
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:\xampp\php
You can echo $PATH to see the PATH variable in the shell.
If you run the command cmd, it will update all system variables for that command window.
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_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\Batchfile.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
HKCU\Software\Microsoft\Command 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.
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.
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.)
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.
I have installed PHP that time. I extracted php-7***.zip into C:\php</i>
Back up my current PATH environment variable: run cmd, and execute command: path >C:\path-backup.txt
Get my current path value into C:\path.txt file (the same way)
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:\Windows\System32; or C:\Windows\System32\Wbem; - I've got twice.
Remove uninstalled programs paths as well. Example: C:\Program Files\NonExistSoftware;
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!!!
Open Windows PowerShell as Administrator (e.g., Win + X).
Run command:
setx path "Here you should insert string from buffer (new path value)"
Rerun your terminal (I use "Far Manager") and check:
php -v
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
right-click on "This PC"
Click on "Properties"
On the left panel of the window that pops up, click on "Advanced System Settings"
Click on the "Advanced" tab
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
via
Windows 7
via
Windows XP
via
On Windows 10, I was able to search for set path environment variable and got these instructions:
From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
From the Power User Task Menu, click System.
In the Settings window, scroll down to the Related settings section and click the System info link.
In the System window, click the Advanced system settings link in the left navigation panel.
In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
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:\Winnt\System32
The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.

Resources