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

指南:

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

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

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


当前回答

不知道这在批处理文件中有多有用,但在命令提示符中使用它是一个非常方便的命令:

C:\some_directory> start .

这将在“some_directory”文件夹中打开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参考页面。

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。

使用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!

删除周围的报价。

for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a

我最近必须写一个批处理文件,由VS预构建事件调用,我想在项目目录中作为参数传递。在批处理文件中,我需要将路径与嵌套子文件夹名称连接起来,但首先需要删除周围的引号。

隐藏交互式批处理脚本的输入:

  @echo off

  echo hP1X500P[PZBBBfh#b##fXf-V@`$fPf]f3/f1/5++u5>in.com

  set /p secret_password="Enter password:"<nul

  for /f "tokens=*" %%i in ('in.com') do (set secret_password=%%i)

  del in.com