简单例子1:
@echo off
if not exist "%SystemRoot%\" if not exist "C:\Windows2" goto MissingFolderFile
echo Found either the directory %SystemRoot% or the file/folder C:\Windows2.
rem Insert here more commands to run on either the folder C:\Windows
rem or the file/folder (=any file system entry) C:\Windows2 existing.
goto EndDemo
:MissingFolderFile
echo There is neither the directory %SystemRoot% nor the file/folder C:\Windows2.
rem Insert here more commands to run on neither folder C:\Windows
rem nor file/folder C:\Windows2 existing.
:EndDemo
pause
Windows 命令处理器旨在处理一个接一个的命令行,这就是这个词的含义batch。命令GOTO是在批处理文件中使用的首选命令,以继续批处理,而不是在下一个命令行上,而是在另一个命令行上,具体取决于IF条件,即将处理从一个命令行堆栈(即批处理)更改为另一组命令行。
简单例子2:
@echo off
if exist "%SystemRoot%\" goto FolderExists
if exist "C:\Windows2" goto FS_EntryExists
echo There is neither the directory %SystemRoot%\ nor C:\Windows2.
rem Insert here more commands to run on neither folder C:\Windows
rem nor file/folder/reparse point C:\Windows2 existing.
goto EndDemo
:FS_EntryExists
echo The file system entry (file or folder) C:\Windows2 exists.
rem Insert here more commands to run on C:\Windows2 existing.
goto EndDemo
:FolderExists
echo The folder %SystemRoot% exists.
rem Insert here more commands to run on folder C:\Windows existing.
:EndDemo
pause
要了解所使用的命令及其工作原理,请打开命令提示符 https://www.howtogeek.com/235101/10-ways-to-open-the-command-prompt-in-windows-10/窗口中,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。
echo /?
goto /?
if /?
rem /?
NOTE:
Windows 上的目录分隔符是\
并不是/
就像在 Linux 或 Mac 上一样。 Windows 文件管理通常会自动替换所有/
by \
在将不带或带通配符模式的文件/文件夹参数字符串传递到文件系统之前,如 Microsoft 在有关文档中所解释的命名文件、路径和命名空间 https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file。但使用/
代替\
然而,文件/文件夹参数字符串可能会导致意外行为。
由于使用而导致意外行为的示例/
直接在命令提示符窗口中运行以下命令行:
for %I in ("%SystemDrive%/Windows/*.exe") do @if exist "%I" (echo Existing file: "%I") else echo File not found: "%I"
该命令行输出由以下命令找到的可执行文件名列表FOR在不存在命令的 Windows 目录中IF只是因为使用/
导致将找到的不带路径的文件名分配给循环变量。因此,仅当系统驱动器上的当前目录恰好是 Windows 目录时,此命令行才有效。
使用相同的命令行\
作为目录分隔符:
for %I in ("%SystemDrive%\Windows\*.exe") do @if exist "%I" (echo Existing file: "%I") else echo File not found: "%I"
此命令行将 Windows 目录中可执行文件的每个文件名输出为带有完整路径的现有文件。
另一个例子:
当前驱动器根目录下有一个目录Downloads
该驱动器上的当前目录是Temp
, 例如D:\Downloads
是想要的当前目录并且D:\Temp
是当前目录。
使用的命令是:
cd /Downloads
结果是错误信息:
该系统找不到指定的路径。
正确使用目录分隔符的命令:
cd \Downloads
该命令适用于D:\Temp
是当前目录并且D:\Downloads
现存的。
CD解释不正确/Downloads
字符串/D
在目录路径的开头作为选项/D
还要更改驱动器并搜索该原因ownloads
在当前目录中而不是Downloads
在当前驱动器的根目录中。这种错误的解释是CD通过使用正确的目录参数字符串可以避免\Downloads
.
概括:\
是目录分隔符并且/
用于命令选项。