Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
当前回答
一行中包含多个命令,在很多情况下都很有用:
&用于组合两个命令,执行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
其他回答
使用copy追加文件:
copy file1.txt+file2.txt+file3.txt append.txt
另外,将所有CLI参数设置为一个变量:
SET MSG=%*
这将使用空格分隔的每个单词(或符号)并将其保存到单个批处理文件变量中。从技术上讲,每个参数都是%1、%2、$3等等,但是这个SET命令使用通配符来引用stdin中的每个参数。
批处理文件:
@SET MSG=%*
@echo %MSG%
命令行:
C:\test>test.bat Hello World!
Hello World!
使用管道'|'命令查找文件夹中的文件中的字符串:
dir /b *.* | findstr /f:/ "thepattern"
创建并开始编辑一个新文件
copy con new.txt
This is the contents of my file
^Z
Ctrl+Z发送ASCII EOF字符。这就像bash中的heredocs:
cat <<EOF > new.txt
This is the contents of my file
EOF
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 :)
没有编辑器,需要创建一个批处理文件?
copy con test.bat
只需输入命令,按enter键输入新行。 按Ctrl-Z和Enter关闭文件。