我有一个批处理文件,位于 USB 密钥上。我需要知道批次所在的驱动器名称。
例如,如果它是 E:\mybatch.bat,则打开时应该找到 E:\ 与 F:\、G:\ 等相同的内容。
我怎样才能在批处理脚本中做到这一点。 (Windows)
%CD%
就是您要找的。它打印批处理文件或运行它的命令的当前工作目录。如果您的批处理文件位于驱动器的根目录下,它只会打印驱动器号,否则您必须解析前 2 个字符。
示例:
echo %CD%
打印
E:\
在安装到 E: 的闪存驱动器上。
更新:正如 Andriy 在评论中所说,如果您只是查找路径的前三个字符,请使用它而不是 %CD%:
%CD:~0,3%
这将导致
E:\
,例如,驱动器上的任何位置。
M$ 文档“使用批处理参数”说:
修饰符:%~d0
描述:将 %0 扩展为驱动器号。
这个问题的现有答案并不承认这个问题实际上是在问两个不同的事情:
当前工作目录的驱动器
%CD:~0,2%
C:
。
批处理文件本身的驱动器
%~d0
这会将批处理文件的完整路径(在%0
中)修剪为仅一个驱动器号和一个冒号,例如
C:
。
(这是我的拒绝编辑
Kai K的答案的扩展版本) 如果从 .CMD/.BAT 文件内部运行,您可以使用
%~dp0
在 Win 11 版本 23H2 对我来说,假设它是 C:
非常感谢@Sparky3489,如果我只有一个 USB 闪存驱动器,我会将其放入您的算法中,就在
之后我还将标识符的措辞更改为
Echo %%i is a USB Flash Drive~!
然后,在算法之后{和外部},我可以添加闪存驱动器路径,例如...
Set FlashPath=%FlashDrive%\Users\Public\Documents
然后通过设置其他Path 比如
Set SourcePath=C:\Users\Public\Documents
我可以为闪存驱动器制作批处理文件备份(可以通过 Windows 快捷方式在快速启动窗口中使用关联图标来调用 ~ 搜索“快速启动”,如果对我所说的内容有疑问)。
Rem * * * * * * * * * Start Batch File * * * * * * * * * *
@Echo OFF
cls
Echo FlashDrive UpDater for
Echo.
Echo Excel, Word ...
Echo * * * * * * * * * ~ Excel SpreadSheets ~ * * * * * * * * *
XCopy /D /I /V /Y /U /S "%SourcePath%\Excel Documents\*.*" "%FlashPath%\Excel Documents\"
Echo * * * * * * * * * ~ Word Documents ~ * * * * * * * * *
XCopy /D /I /V /Y /U /S "%SourcePath%\Word Documents\*.*" "%FlashPath%\Word Documents\"
Echo.
Echo.
Echo FlashDrive = %FlashDrive%
Echo FlashPath = %FlashPath%
Echo.
Echo * Bonus Switch Info * * * * *
Echo * XCopy Switch /D ~ Copies Files Changed On or After the Specified Date.
Echo * {If no Date is Given, Copies only those Files whose
Echo * Source Time is Newer than the Destination Time}.
Echo * XCopy Switch /I ~ Copies More than One File to Destination (Assumes Destination is a Directory)
Echo * XCopy Switch /S ~ Copies Directories and Subdirectories Except Empty Ones
Echo * XCopy Switch /V ~ Verifies Each New File.
Echo * XCopy Switch /U ~ Copies only Files that Already Exist in Destination.
Echo * XCopy Switch /Y ~ Suppresses Prompting to Confirm You Want to Overwrite an Existing Destination File.
Echo.
Rem for More Info on XCopy Switches GoTo http://support.microsoft.com/kb/128756
Echo Directory Path = %~DP0
Echo.
Echo * Batch File Name = %0 *
Echo.
Rem Echo %CD:~0,2%, {Returns "Drive Letter & Colon"}
Rem Echo %CD:~0,3%, {Returns "Drive Letter & Colon & BackSlash"}
Pause
cls
Pause
Exit
Rem * * * * * * * * * End Batch File * * * * * * * * * *
%CD:~0,2%
C:
的当前驱动器,即当前工作目录中的前 2 个字符
C:\Users\ashish>ECHO %CD:~0,2%
C:
D:\projects>ECHO %CD:~0,2%
D:
D:\projects>ECHO %CD%
D:\projects
就像其他人说的那样
%~d0
没有必要再次讨论这个问题,但是如果您偶然发现了这个线程,那么这将 cd 到批处理文件的目录。
@echo off
set "fullDir=C:\Program Files"
cd /d %fullDir% &rem changes to the full directory 'C:\Program Files'.
echo You're now cd' in the '%cd%' directory.
pause
此外,如果您想从另一个驱动器(例如
Z:
)运行批处理文件,那么这个就可以做到。
cd /d %~d0 &rem Changes to the current directory
echo You're now cd' in the '%cd%' directory. &rem This is now your full path of the batch file cd' into.
pause