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

指南:

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

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

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


当前回答

这个批处理文件既可以使用简单文件,也可以使用目录作为命令行参数(您可以以任何顺序混合它们)。循环在任何指定的文件上运行命令(本例中为'echo'),如果一个参数是一个目录,它将在其中的每个文件上递归地运行命令。

@echo off
for /f "delims=" %%f in ('dir %* /a-d /b /s') do echo %%f

其他回答

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宏';'来工作,当它被解释为批处理文件时,它会被优雅地(或无声地)忽略。

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

支持正则表达式的Findstr:

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

Forfiles非常有用,例如,递归删除所有超过两天的文件

forfiles /D -2 /P "C:\Temp" /S /C "cmd /c del @path"

递归搜索目录树中的字符串:

findstr /S /C:"string literal" *.*

你也可以使用正则表达式:

findstr /S /R "^ERROR" *.log

递归文件搜索:

dir /S myfile.txt

基于行的执行

虽然在大多数情况下没有明显的好处,但当试图在运行时更新内容时,它会有所帮助。例如:

UpdateSource.bat

copy UpdateSource.bat Current.bat
echo "Hi!"

Current.bat

copy UpdateSource.bat Current.bat

现在,执行Current.bat会产生这样的输出。

HI!

注意,批处理执行是按行号进行的。如果基本行没有完全相同的行号,这样的更新可能会导致跳过或向后移动一行。