问题
Firstly, I saw this topic but I couldn\'t understand that.
Question :
There is a batch file in D:\\path\\to\\file.bat
with following content :
echo %cd%
pause
Output is :
C:\\
It must be D:\\path\\to
What am I doing wrong?
回答1:
System read-only variable %CD%
keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0
(e.g. scripts\mybatch.bat
). Parameter extensions can be applied to this so %~dp0
will return the Drive and Path to the batch script (e.g. W:\scripts\
) and %~f0
will return the full pathname (e.g. W:\scripts\mybatch.cmd
).
You can refer to other files in the same folder as the batch script by using this syntax:
CALL %0\..\SecondBatch.cmd
This can even be used in a subroutine, Echo %0
will give the call label but, echo "%~nx0"
will give you the filename of the batch script.
When the %0
variable is expanded, the result is enclosed in quotation marks.
More on batch parameters.
回答2:
Very simple:
setlocal
cd /d %~dp0
File.exe
回答3:
Within your .bat file:
set mypath=%cd%
You can now use the variable %mypath%
to reference the file path to the .bat
file. To verify the path is correct:
@echo %mypath%
For example, a file called DIR.bat
with the following contents
set mypath=%cd%
@echo %mypath%
Pause
run from the directory g:\test\bat
will echo that path in the DOS command window.
回答4:
Here's what I use at the top of all my batch files. I just copy/paste from my template folder.
@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"
Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.
Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.
:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt
Of course, Powershell does this and lots more.
来源:https://stackoverflow.com/questions/17063947/get-current-batchfile-directory