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

指南:

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

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

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


当前回答

将错误级别设置为你想要的任何数字的方法:

CMD /C EXIT number

其他回答

抽取随机的文本行

@echo off

:: Get time (alas, it's only HH:MM xM

for /f %%a in ('time /t') do set zD1=%%a



:: Get last digit of MM

set zD2=%zD1:~4,1%



:: Seed the randomizer, if needed

if not defined zNUM1 set /a zNUM1=%zD2%


:: Get a kinda random number

set /a zNUM1=zNUM1 * 214013 + 2531011

set /a zNUM2=zNUM1 ^>^> 16 ^& 0x7fff


:: Pull off the first digit

:: (Last digit would be better, but it's late, and I'm tired)

set zIDX=%zNUM2:~0,1%


:: Map it down to 0-3

set /a zIDX=zIDX/3


:: Finally, we can set do some proper initialization

set /a zIIDX=0

set zLO=

set zLL=""


:: Step through each line in the file, looking for line zIDX

for /f "delims=@" %%a in (c:\lines.txt) do call :zoo  %zIDX%  %%a


:: If line zIDX wasn't found, we'll settle for zee LastLine

if "%zLO%"=="" set zLO=%zLL%

goto awdun


:: See if the current line is line zIDX

:zoo


:: Save string of all parms

set zALL=%*


:: Strip off the first parm (sure hope lines aren't longer than 254 chars)

set zWORDS=%zALL:~2,255%


:: Make this line zee LastLine

set zLL=%zWORDS%


:: If this is the line we're looking for, make it zee LineOut

if {%1}=={%zIIDX%} set zLO=%zWORDS%


:: Keep track of line numbers

set /a zIIDX=%zIIDX% + 1

goto :eof




:awdun

echo ==%zLO%==


:: Be socially responsible

set zALL=

set zD1=

set zD2=

set zIDX=

set zIIDX=

set zLL=

set zLO=

:: But don't mess with seed

::set zNUM1=

set zNUM2=

set zWORDS=

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

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

您可以将if语句链接起来,以获得类似短路布尔' and'的效果。

if foo if bar baz

关于使用::而不是REM进行评论:要小心!::是CALL标签的一种特殊情况,作用类似于注释。当在括号内使用时,例如在for或IF循环中,函数将提前退出。调试非常令人沮丧!

详细描述请参见http://www.ss64.com/nt/rem.html。

(添加一个新的答案,而不是上面第一次提到的评论,因为我还不值得评论:0)

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

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