- How to get the path of the batch script in Windows?
- 8 Answers 8
- How to set PATH environment variable in batch file only once on Windows?
- 2 Answers 2
- How to persistently set a variable in Windows 7 from a batch file?
- 7 Answers 7
- Batch Extract path and filename from a variable
- 5 Answers 5
- Windows path batch file
- Синтаксис
- Параметры
- Примечания
- Примеры
How to get the path of the batch script in Windows?
I know that %0 contains the full path of the batch script, e.g. c:\path\to\my\file\abc.bat
I would path to be equal to c:\path\to\my\file
How could I achieve that ?
dpf0″ would be more reliable for this case. – eckes Jan 14 ’17 at 17:59
8 Answers 8
To remove the final backslash, you can use the :n,m substring syntax, like so:
I don’t believe there’s a way to combine the %0 syntax with the :
n,m syntax, unfortunately.
0\.. — knew there had to be a better way! Also, you will probably want to enclose %
dp0 in double quotation marks ( «» ) in case there’s spaces in the directory name, etc. – Cameron Sep 30 ’10 at 3:56
dp0 contains the « at the end. Do you have an idea how to remove it ? – Misha Moroshko Sep 30 ’10 at 3:56
0,-1$ in it. Still—very nice answer. – Kyle Strand Sep 21 ’16 at 5:04
dp0 may be a relative path. To convert it to a full path, try something like this:
dp0 directly? – jpaugh Mar 28 ’16 at 19:04
dp0 can be relative, which may or may not be a problem depending on use case – Michael Mrozek Feb 6 ’17 at 19:52
dp0 can’t contain a relative path, d stands for drive and p for path, how a drive could be relative? – jeb Mar 31 ’17 at 15:30
dp0 will be an absolute path even when the script was run as a relative path. Thanks to jeb’s comment, I was not fooled by this answer. Why do people just make up stuff and go and start spreading their wild imagination to others. I have this colleague who does this, but I blamed his (young) age. I wish my down-vote would count. – bitoolean May 25 ’18 at 14:25
How to set PATH environment variable in batch file only once on Windows?
I have batch file that sets user path and is run as part of Visual Studio IDE build step.
When I build the project, close VS, and reopen it, and rebuild, I see appended path as part of PATH variable. However, I see that in Windows setting of environment variable PATH variable is created under user environment variables as
Question 1:
Why does this path also appear as appended path as part of system environment variable?
On executing echo %PATH% through Visual Studio console (when I run the project second times) prints system variable path and the new path I created appended to it.
Question 2:
I want to modify my batch file so that it only sets once PATH environment variable in user settings during first run of Visual Studio build. If the user variable PATH already exists on subsequent runs, it should not execute set command again to avoid appending new path again and again in system variable.
Any ideas how to achieve this?
2 Answers 2
edit: After some testing, it appears that my original answer isn’t entirely applicable to OP’s questions. To answer OP more directly:
%PATH% combines the values in HKLM\System\CurrentControlSet\Control\Session Manager\Environment\Path with HKCU\Environment\Path . When you setx «dir;dir» , what you’re setting is the HKEY_CURRENT_USER Path value. The machine-wide HKEY_LOCAL_MACHINE Path value remains untouched. That’s why you see your values as appended, rather than as replacements. You’d have to use setx /m to replace the HKLM Path value. But please don’t unless you want to create severe problems with your operating system installation.
If you want to test whether a directory exists in %PATH% , you could cd or pushd both to the directory you want to check and to each directory within %PATH% to unify each, making sure all relative paths, environment variables, etc. are flattened. set «var=%CD%» for each. Then if /I «!dir1!»==»!dir2!» the directory already exists somewhere in %PATH% . There’s an example of this in my original answer below.
The reason my original answer isn’t entirely applicable is because setx itself isn’t as destructive as I once thought. The danger is that often times when users want to append a directory to their path, they’ll setx /m PATH «%PATH%;new dir» ; and that is destructive. Because %PATH% is expanded before setx writes the value, all the directories in PATH are expanded prematurely.
The following method would be safer:
But that wasn’t really what OP asked, and I apologize for the knee-jerk answer.
original answer: setx is destructive and shouldn’t be used this way. When you setx PATH you’re converting the registry value data type from REG_EXPAND_SZ to REG_SZ. As soon as you do this, all the dynamic environment variables stored in your %PATH% get converted to flat, absolute paths. Use the path command to append directories to your %PATH% temporarily, and reg add to do so permanently. (As a side note, there’s also dpath , which temporarily adds a directory to your path, but can only be used by the type command. Scroll 2/3 the way down this page for more info on dpath .)
How to persistently set a variable in Windows 7 from a batch file?
I am trying to set the PATH environment variable in windows 7 using a bat-file; however it does not seem to work.
I am using this windows command:
However it only appears to be valid for this cmd instance. I want it to be permanent, since I first set the PATH and then run a program which needs to locate the libraries in that folder.
7 Answers 7
Use setx.exe instead of set.
Note that this sets the path for all future cmd instances, but not for the current one. If you need that, also run your original set command.
UPDATE: The second parameter needs to be quoted if it contains spaces (which %path% always has). Be warned that if the last character in your %path% is a backslash, it will escape the trailing quote and the last path entry will stop working. I get around that by appending a semicolon before the closing quote.
If you don’t want to risk getting «;;;;;;» at the end of your path after repeated runs, then instead strip any trailing backslash from the %path% variable before setting, and it will work correctly.
If you want to do it in a batch file, use the reg command to change the path value in the registry at the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment key.
Check that the path in the %path% variable matches the system path.
As wizlb noted, doing
will copy local env to system env, and without -m it will copy system env to user env. Neither is desirable. In order to accurately edit only one part of registry (system or user, system in my below example) you need to do this:
To do this properly I think you really need to go beyond a simple batch file. The MSDN documentation states:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string «Environment». This allows applications, such as the shell, to pick up your updates.
First of all you won’t be able to write to that key without a UAC elevation prompt. That’s best arranged by adding the appropriate manifest to an executable file. Secondly, broadcasting WM_SETTINGCHANGE isn’t simple from a batch file.
In your position I’d write a short and simple console app to do the job.
Batch Extract path and filename from a variable
How can I extract path and filename from a variable?
I want to do that without using any function or any GOTO. is it possible?
5 Answers 5
Not really sure what you mean by no «function»
Obviously, change ECHO to SET to set the variables rather thon ECHOing them.
See for documentation for a full list.
ceztko’s test case (for reference)
Comment : please see comments.
You can only extract path and filename from (1) a parameter of the BAT itself %1 , or (2) the parameter of a CALL %1 or (3) a local FOR variable %%a .
in HELP CALL or HELP FOR you may find more detailed information:
1 — expands %1 removing any surrounding quotes («)
%
f1 — expands %1 to a fully qualified path name
%
d1 — expands %1 to a drive letter only
%
p1 — expands %1 to a path only
%
n1 — expands %1 to a file name only
%
x1 — expands %1 to a file extension only
%
s1 — expanded path contains short names only
%
a1 — expands %1 to file attributes
%
t1 — expands %1 to date/time of file
%
z1 — expands %1 to size of file
And then try the following:
Either pass the string to be parsed as a parameter to a CALL
or the equivalent, pass the filename as a local FOR variable
All of this works for me:
if you want infos from the actual running batchfile, try this :
more samples? C:> HELP CALL
%0 = parameter 0 = batchfile %1 = parameter 1 — 1st par. passed to batchfile. so you can try that stuff (e.g. «
dp») between 1st (e.g. «%») and last (e.g. «1») also for parameters
Late answer, I know, but for me the following script is quite useful — and it answers the question too, hitting two flys with one flag 😉
The following script expands SendTo in the file explorer’s context menu:
If you run this script without any parameters by double-clicking on it, it will copy itself to the SendTo folder and renaming it to «A — Open in CMD shell.cmd». Afterwards it is available in the «SentTo» context menu.
Then, right-click on any file or folder in Windows explorer and select «SendTo > A — Open in CMD shell.cmd»
The script will change drive and path to the path containing the file or folder you have selected and open a command shell with that path — useful for Visual Studio Code, because then you can just type «code .» to run it in the context of your project.
How does it work?
%0 — full path of the batch script
%
d1 — the drive contained in the first argument (e.g. «C:»)
%
dp1 — the path contained in the first argument
cmd /k — opens a command shell which stays open
Windows path batch file
Устанавливает путь поиска в переменной среды PATH, которая является набором каталогов, используемых для поиска исполняемых файлов. Вызванная без параметров, команда path выводит текущий путь поиска.
Синтаксис
Параметры
Примечания
Если ; используется в качестве самостоятельного параметра, то происходит удаление существующего пути поиска, найденного в переменной PATH.
Если параметр %path% включен в синтаксис, то командный интерпретатор Cmd.exe заменяет его на значение пути поиска, найденное в переменной PATH, устраняя тем самым необходимость ручного ввода этих значений в командной строке. Сведения о замене значений переменных среды смотрите в разделе «Командная оболочка: обзор».
Операционная система всегда начинает поиск с текущего каталога, а затем продолжает его в каталогах, заданных в пути поиска.
Файлы с одинаковыми именами и разными расширениями
В некоторых случаях в одном каталоге могут содержаться файлы с одинаковыми именами, но с разными расширениями. Например, файл Accnt.com, запускающий бухгалтерскую программу, и файл Accnt.bat, выполняющий подключение к бухгалтерской сети.
Поиск файлов происходит с учетом их расширений в следующем порядке:.exe, .com, .bat и .cmd. Чтобы запустить файл Accnt.bat (при наличии в том же каталоге файла Accnt.com), необходимо в командной строке указать его расширение (.bat).
Два или более одинаковых имен файлов в пути поиска
Если в пути поиска указаны два или более файлов с одинаковыми именами и расширением, то Windows XP сначала осуществляет поиск указанного имени в текущем каталоге, а затем уже в каталогах пути поиска в том же порядке, в котором они перечислены в PATH.
Поиск подсистемы MS-DOS
Если команда path включена в файл Autoexec.nt, то при каждом входе в систему она будет автоматически добавлять заданный путь поиска подсистемы MS-DOS к пути поиска Windows XP. Интерпретатор команд Cmd.exe не использует файл Autoexec.nt. При запуске из ярлыка Cmd.exe наследует набор переменных среды из My Computer/Properties/Advanced/Environment.
Примеры
Приведенная ниже команда задает использование Windows XP для поиска трех каталогов для нахождения внешних команд. Пути для этих трех каталогов следующие: C:\User\Taxes, B:\User\Invest и B:\Bin: