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

指南:

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

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

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


当前回答

允许您更改目录基于环境变量没有 必须指定'%'指令。如果指定的变量没有 存在,然后尝试目录名。

@if defined %1 (call cd "%%%1%%") else (call cd %1)

其他回答

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

现在很多人使用GOTO:EOF来终止他们的批处理文件,但你也可以使用EXIT /B来达到这个目的。

使用EXIT /B的优点是你可以在EXIT /B之后添加一个错误级别,它将退出该错误级别。

批处理脚本最常见的需求之一是记录生成的输出,以供以后检查。是的,您可以将stdout和stderr重定向到一个文件,但是您无法看到发生了什么,除非您跟踪日志文件。

因此,考虑使用stdout/stderr日志记录工具运行您的批处理脚本,例如logger,它将使用时间戳记录输出,并且您仍然能够看到脚本进程。

另一个stdout/stderr日志记录实用程序

Yet another stdout/stderr logging utility [2010-08-05]
Copyright (C) 2010 LoRd_MuldeR <MuldeR2@GMX.de>
Released under the terms of the GNU General Public License (see License.txt)

Usage:
  logger.exe [logger options] : program.exe [program arguments]
  program.exe [program arguments] | logger.exe [logger options] : -

Options:
  -log <file name>  Name of the log file to create (default: "<program> <time>.log")
  -append           Append to the log file instead of replacing the existing file
  -mode <mode>      Write 'stdout' or 'stderr' or 'both' to log file (default: 'both')
  -format <format>  Format of log file, 'raw' or 'time' or 'full' (default: 'time')
  -filter <filter>  Don't write lines to log file that contain this string
  -invert           Invert filter, i.e. write only lines to log file that match filter
  -ignorecase       Apply filter in a case-insensitive way (default: case-sensitive)
  -nojobctrl        Don't add child process to job object (applies to Win2k and later)
  -noescape         Don't escape double quotes when forwarding command-line arguments
  -silent           Don't print additional information to the console
  -priority <flag>  Change process priority (idle/belownormal/normal/abovenormal/high)
  -inputcp <cpid>   Use the specified codepage for input processing (default: 'utf8')
  -outputcp <cpid>  Use the specified codepage for log file output (default: 'utf8')

使用pushd到UNC路径将创建一个临时驱动器映射(从Z开始,向后查找下一个可用的字母),并将您放入该驱动器和路径中。弹出或退出命令提示符时,临时映射将消失。

   C:\>pushd \\yourmom\jukebox

   Z:\>pushd \\yourmom\business

   Y:\>

此外,与其说这是一个批处理技巧,不如说这是一个命令行环境技巧,但是当您在命令行上使用pushd和popd和网络共享时,使用$+(显示pushd堆栈深度)和$M(显示网络共享路径)修改提示符是有用的。

   C:\utils>prompt $+$m$p$g

   C:\utils>pushd m:

   +\\yourmom\pub M:\>pushd c:\

   ++c:\>pushd
   M:\
   C:\utils  

   ++c:\>popd

   +\\yourmom\pub M:\>popd

   C:\utils>

相当于bash(和其他shell)

echo -n Hello # or
echo Hello\\c

输出“Hello”,后面没有换行符。一个cmd黑客来做这个:

<nul set /p any-variable-name=Hello

Set /p是一种提示用户输入的方法。它发出给定的字符串,然后等待(在同一行,即没有CRLF),等待用户输入响应。

<nul只是向set /p命令输送一个空响应,因此最终结果是发出的提示字符串。(由于响应为空,所使用的变量保持不变。)

问题是:不可能输出前导等号,在Vista中前导空白字符被删除,但在XP中没有。