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

指南:

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

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

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


当前回答

dos命令宏。

我已经很久没有参考过这一点了,但我仍然认为这是一个好主意,值得分享。

我们可以将批处理文件和doskey脚本合并到一个文件中。这可能看起来有点过于聪明,但它确实有效。

;= @echo off
;= rem Call DOSKEY and use this file as the macrofile
;= %SystemRoot%\system32\doskey /listsize=1000 /macrofile=%0%
;= rem In batch mode, jump to the end of the file
;= goto end

;= Doskey aliases
h=doskey /history

;= File listing enhancements
ls=dir /x $*

;= Directory navigation
up=cd ..
pd=pushd

;= :end
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line.  It clears out the ';' 
;= rem * macro. Were using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=

它通过定义一个假的doskey宏';'来工作,当它被解释为批处理文件时,它会被优雅地(或无声地)忽略。

我缩短了这里列出的版本,如果你想要更多,请点击这里。

其他回答

调用集——将环境变量展开几个层次。

在http://ss64.com/nt/call.html#advanced从另一个SO问题的答案中发现这个批处理文件变量在for循环中初始化

set VarName=Param
set Param=This

call set Answer=%%%Varname%%%
Echo %Answer%

给了

set VarName=Param
set Param=This
call set Answer=%Param%
Echo This
This

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

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

变量的延迟展开(为了更好地度量,还加入了子字符串):

    @echo off
    setlocal enableextensions enabledelayedexpansion
    set full=/u01/users/pax
:loop1
    if not "!full:~-1!" == "/" (
        set full2=!full:~-1!!full2!
        set full=!full:~,-1!
        goto :loop1
    )
    echo !full!
    endlocal

相当于bash(和其他shell)

echo -n Hello # or
echo Hello\\c

输出“Hello”,后面没有换行符。一个cmd黑客来做这个:

<nul set /p any-variable-name=Hello

Set /p是一种提示用户输入的方法。它发出给定的字符串,然后等待(在同一行,即没有CRLF),等待用户输入响应。

<nul只是向set /p命令输送一个空响应,因此最终结果是发出的提示字符串。(由于响应为空,所使用的变量保持不变。)

问题是:不可能输出前导等号,在Vista中前导空白字符被删除,但在XP中没有。

一个非常古老(大约1990年)的技巧来获得环境变量的总大小:

set > test
dir test
del test