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

指南:

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

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

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


当前回答

为了从脚本内部解析stdin,你需要使用For和FIND命令:

for /f "tokens=*" %%g in ('find /V ""') do (
     :: do what you want with %%g
     echo %%g
)

其他回答

狡猾的等待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

使用&::的内联注释。

:: This is my batch file which does stuff.
copy thisstuff thatstuff  &:: We need to make a backup in case we screw up!

:: ... do lots of other stuff

这是如何工作的呢?这是一个丑陋的黑客。&是命令分隔符,大致近似于;UNIX shell。::是另一个丑陋的黑客,有点像REM语句。最终结果是执行命令,然后执行一个什么都不做的命令,从而近似于注释。

这并不是在所有情况下都有效,但它通常足够有用。

现在很多人使用GOTO:EOF来终止他们的批处理文件,但你也可以使用EXIT /B来达到这个目的。

使用EXIT /B的优点是你可以在EXIT /B之后添加一个错误级别,它将退出该错误级别。

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。

IF命令!没有它,我的批处理文件是垃圾!

@echo off
IF exist %windir%\system32\iexplore.exe goto end

echo Hmm... it seems you do not have Internet Explorer.
echo Great! You seem to understand ;)

:end
echo Hmm... You have Internet Explorer.
echo That is bad :)