Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
当前回答
能够运行命令并处理输出(如bash中的'$()'的反引号)。
for /f %i in ('dir /on /b *.jpg') do echo --^> %i
如果文件名中有空格,可以这样写:
for /f "tokens=*" %i in ('dir /on /b *.jpg') do echo --^> %i
其他回答
脚本所在的路径(带驱动器):~dp0
set BAT_HOME=%~dp0
echo %BAT_HOME%
cd %BAT_HOME%
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宏';'来工作,当它被解释为批处理文件时,它会被优雅地(或无声地)忽略。
我缩短了这里列出的版本,如果你想要更多,请点击这里。
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。
您可以在批处理文件运行时修改它。例如,如果您希望在批处理文件退出之前看到结果,您可以在文件运行时在文件的末尾添加一个被遗忘的暂停。
请参见在批处理文件运行时更改批处理文件
我个人认为这更像是一个陷阱,而不是一个功能。
当你想在分支之间复制文件时,一个方便的技巧:
C:\src\branch1\mydir\mydir2\mydir3\mydir4>xcopy %cd:branch1=branch2%\foo*
Overwrite C:\src\branch1\mydir\mydir2\mydir3\mydir4\foo.txt (Yes/No/All)? y
C:\src\branch2\mydir\mydir2\mydir3\mydir4\foo.txt
这既使用了%cd%环境变量,也使用了环境变量替换。