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

指南:

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

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

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


当前回答

符号链接:

mklink /d directorylink ..\realdirectory
mklink filelink realfile

该命令是Windows Server 2008及更新版本(包括Vista和Windows 7)上的本机命令。(它也包含在一些Windows资源包中。)

其他回答

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参考页面。

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

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

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

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

递归文件搜索:

dir /S myfile.txt

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

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

批处理文件中的数组。

设置一个值:

set count=1
set var%count%=42

在命令行提取一个值:

call echo %var%count%%

从批处理文件中提取一个值:

call echo %%var%count%%%

注意额外的扫射%符号。

这项技术可能看起来有点复杂,但它非常有用。如上所述,将打印var1(即42)的内容。如果我们想将其他变量设置为var1中的值,也可以用set替换echo命令。这意味着下面的值在命令行是有效的赋值:

call set x=%var%count%%

然后查看va1的值:

echo %x%

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
)

非常快速有效。