Ham*_*ava 254 windows batch-file working-directory
首先,我看到了这个话题,但我无法理解.
题 :
有一个D:\path\to\file.bat
包含以下内容的批处理文件:
echo %cd%
pause
Run Code Online (Sandbox Code Playgroud)
输出是:
C:\
Run Code Online (Sandbox Code Playgroud)
肯定是 D:\path\to
我究竟做错了什么?
Sto*_*leg 461
系统只读变量%CD%
保留批处理调用方的路径,而不是批处理文件位置.
您可以获取用户键入的批处理脚本本身的名称%0
(例如scripts\mybatch.bat
).参数扩展可以应用于此,因此%~dp0
将返回批处理脚本的驱动器和路径(例如W:\scripts\
)并%~f0
返回完整路径名(例如W:\scripts\mybatch.cmd
).
您可以使用以下语法引用与批处理脚本相同的文件夹中的其他文件:
CALL %0\..\SecondBatch.cmd
Run Code Online (Sandbox Code Playgroud)
这甚至可以在子例程中使用,Echo %0
将给出调用标签,但是,echo "%~nx0"
将为您提供批处理脚本的文件名.
当%0
变量被扩展,结果是包含在引号.
sha*_*hay 109
非常简单:
setlocal
cd /d %~dp0
File.exe
Run Code Online (Sandbox Code Playgroud)
小智 28
在.bat文件中:
set mypath=%cd%
Run Code Online (Sandbox Code Playgroud)
您现在可以使用该变量%mypath%
来引用文件的文件路径.bat
.要验证路径是否正确:
@echo %mypath%
Run Code Online (Sandbox Code Playgroud)
例如,DIR.bat
使用以下内容调用的文件
set mypath=%cd%
@echo %mypath%
Pause
Run Code Online (Sandbox Code Playgroud)
从目录运行g:\test\bat
将在DOS命令窗口中回显该路径.
小智 14
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%"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Of course, Powershell does this and lots more.
归档时间: |
|
查看次数: |
395349 次 |
最近记录: |