Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?

指南:

每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包

澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。

(请参见:Windows批处理文件:.bat vs .cmd?)


当前回答

我使用它们作为常用目录的快捷方式。 一个名为“sandbox.bat”的示例文件,它位于我的PATH目录中

EXPLORER "C:\Documents and Settings\myusername\Desktop\sandbox"

调用脚本只需WIN+R—>沙盒

其他回答

命令分隔符:

cls & dir
copy a b && echo Success
copy a b || echo Failure

在第二行,&&之后的命令仅在第一个命令成功时运行。

在第3行,||之后的命令仅在第一个命令失败时运行。

具有数值变量的循环的正确格式是

for /l %%i in (startNumber, counter, endNumber) do echo %%i

更多详情> http://www.ss64.com/nt/for.html

一行中包含多个命令,在很多情况下都很有用:

&用于组合两个命令,执行command1和command2 &&一个条件组合,如果command1成功完成,则执行command2 仅当command1未成功完成时才执行Command2。

例子:

:: ** Edit the most recent .TXT file and exit, useful in a .CMD / .BAT **
FOR /F %%I IN ('DIR *.TXT /B /O:-N') DO NOTEPAD %%I & EXIT


:: ** If exist any .TXT file, display the list in NOTEPAD, if not it 
:: ** exits without any error (note the && and the 2> error redirection)
DIR *.TXT > TXT.LST 2> NUL && NOTEPAD TXT.LST

支持正则表达式的Findstr:

findstr "^[0-9].*" c:\windows\system32\drivers\etc\hosts

无论如何,这是一个很好的Windows CMD或批处理文件的在线参考。我学到了一些我不知道的东西。