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

指南:

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

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

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


当前回答

当向批处理文件传递未知数量的参数时,例如,当几个文件被拖放到批处理文件上以启动批处理文件时,您可以通过名称引用每个参数变量。

TYPE %1
TYPE %2
TYPE %3
TYPE %4
TYPE %5
...etc

但是当你想要检查每个参数是否存在时,这就变得非常混乱了:

if [%1] NEQ [] (
TYPE %1
)
if [%2] NEQ [] (
TYPE %2
)
if [%3] NEQ [] (
TYPE %3
)
if [%4] NEQ [] (
TYPE %4
)
if [%5] NEQ [] (
TYPE %5
)
...etc

此外,使用这种方法只能接受有限数量的参数。

相反,尝试使用SHIFT命令:

:loop
IF [%1] NEQ [] (
TYPE %1
) ELSE (
GOTO end
)
SHIFT
GOTO loop
:end

SHIFT将把所有参数都向下移动一个,因此%2变成%1,%3变成%2,等等。

其他回答

支持正则表达式的Findstr:

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

狡猾的等待N秒的技巧(不是cmd.exe的一部分,但不是额外的软件,因为它是Windows自带的),参见ping行。您需要N+1个ping,因为第一个ping没有延迟。

    echo %time%
    call :waitfor 5
    echo %time%
    goto :eof
:waitfor
    setlocal
    set /a "t = %1 + 1"
    >nul ping 127.0.0.1 -n %t%
    endlocal
    goto :eof

隐藏从命令重定向到>nul 2>&1的所有输出。

例如,某些命令行程序即使重定向到>nul也会显示输出。但是,如果像下面这行那样重定向输出,所有输出都将被抑制。

PSKILL NOTEPAD >nul 2>&1

编辑:有关其工作原理的解释,请参见忽略命令的输出。

There is also the EDLIN command. While it may be an old bastard tool once used for line-based text editing, the fact that it's controllable from the command line makes it rather useful for batch scripting, mostly because, just like any other case you'd be using EDLIN, it's the only tool available. After all, EDLIN is not a tool you would ordinarily want to use for text editing, unless you are somewhat masochistic. To quote Tim Patterson (the fellow who wrote it): "I was aghast when I heard that IBM was using it and not throwing it out the window."

注意:EDLIN将老式的EOF (1A)标记添加到它编辑的文件中。如果需要删除它们,可能必须使用DEBUG。

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

&用于组合两个命令,执行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