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

指南:

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

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

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


当前回答

FIND作为grep的替代品。 我用find给自己黑了个电话簿。非常有用:

@echo off
:begin
set /p term=Enter query: 
type phonebookfile.txt |find /i "%term%"
if %errorlevel% == 0 GOTO :choose
echo No entry found
set /p new_entry=Add new entry: 
echo %new_entry% >> phonebookfile.txt 
:choose
set /p action=(q)uit, (n)ew query or (e)dit? [q] 
if "%action%"=="n" GOTO anfang
if "%action%"=="e" (
    notepad phonebookfile.txt
    goto :choose
)

非常快速有效。

其他回答

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

在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

创建并开始编辑一个新文件

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

去:eof纸板

我在脚本的末尾添加了“goto:eof”,作为存放代码片段的方便空间。这样我就可以快速复制/粘贴到这个区域,而不需要注释/取消注释。

goto :eof
:: code scraps
call this.bat
call that.bat
set TS=%DATE:~10%%DATE:~4,2%%DATE:~7,2%-%TIME:~0,2%%TIME:~3,2%%TIME:~6%%
for /R C:\temp\ %%G in (*.bak) DO del %%G

CHOICE命令提示用户在多个选项中选择一个(通过单个按键)

@echo off
echo Please choose one of the following options
echo 1. Apple
echo 2. Orange
echo 3. Pizza
echo a, b, c. Something else
choice /c:123abc /m "Answer?"
set ChoiceLevel=%ErrorLevel%
echo Choice was: %ChoiceLevel%

%ChoiceLevel%将是选中的第n个选项(在上面的例子中,b=5)。

更多详情请访问SS64.com上的CHOICE参考页面。

FIND作为grep的替代品。 我用find给自己黑了个电话簿。非常有用:

@echo off
:begin
set /p term=Enter query: 
type phonebookfile.txt |find /i "%term%"
if %errorlevel% == 0 GOTO :choose
echo No entry found
set /p new_entry=Add new entry: 
echo %new_entry% >> phonebookfile.txt 
:choose
set /p action=(q)uit, (n)ew query or (e)dit? [q] 
if "%action%"=="n" GOTO anfang
if "%action%"=="e" (
    notepad phonebookfile.txt
    goto :choose
)

非常快速有效。