Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
当前回答
没有编辑器,需要创建一个批处理文件?
copy con test.bat
只需输入命令,按enter键输入新行。 按Ctrl-Z和Enter关闭文件。
其他回答
调用集——将环境变量展开几个层次。
在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
当向批处理文件传递未知数量的参数时,例如,当几个文件被拖放到批处理文件上以启动批处理文件时,您可以通过名称引用每个参数变量。
TYPE %1
TYPE %2
TYPE %3
TYPE %4
TYPE %5
...etc
但是当你想要检查每个参数是否存在时,这就变得非常混乱了:
if [%1] NEQ [] (
TYPE %1
)
if [%2] NEQ [] (
TYPE %2
)
if [%3] NEQ [] (
TYPE %3
)
if [%4] NEQ [] (
TYPE %4
)
if [%5] NEQ [] (
TYPE %5
)
...etc
此外,使用这种方法只能接受有限数量的参数。
相反,尝试使用SHIFT命令:
:loop
IF [%1] NEQ [] (
TYPE %1
) ELSE (
GOTO end
)
SHIFT
GOTO loop
:end
SHIFT将把所有参数都向下移动一个,因此%2变成%1,%3变成%2,等等。
批处理脚本最常见的需求之一是记录生成的输出,以供以后检查。是的,您可以将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')
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参考页面。
无论如何,这是一个很好的Windows CMD或批处理文件的在线参考。我学到了一些我不知道的东西。