Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
Windows批处理文件有哪些不太为人所知,但很重要和有用的特性?
指南:
每个答案一个特征 给出特性的简短描述和示例,而不仅仅是文档链接 将答案限制在本地功能,即不需要额外的软件,如Windows资源包
澄清:这里我们指的是由cmd.exe处理的脚本,这是WinNT变体的默认值。
(请参见:Windows批处理文件:.bat vs .cmd?)
当前回答
文件名为“YYYY-MM-DD HH:MM:SS.txt”的例子
回波测试>“%日期:~ 0,4% - %日期:~ 5 2% - %日期:~ 8,2% %时间:~ 0,2% _ %时间:~ 3,2% _ %时间:~ 6,2% . txt”
我使用颜色来指示我的脚本是否成功,失败,或者通过改变文本和背景的颜色来需要一些输入。当你有一些机器在你视野范围内,但距离很远时,它真的很有帮助
颜色XY
其中X和Y为从0到F的十六进制值,其中X -背景,Y -文本,当X = Y时颜色不会改变。
颜色Z
更改文本颜色为“Z”并设置黑色背景,“颜色0”将不起作用
颜色的名字叫
颜色吗?
其他回答
批处理脚本最常见的需求之一是记录生成的输出,以供以后检查。是的,您可以将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')
FOR命令!虽然我讨厌写批处理文件,但我很感激它。
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
将解析myfile.txt中的每一行,忽略以分号开头的行,将每行的第2和第3个标记传递给for主体,标记由逗号和/或空格分隔。 注意for语句引用%i获取第二个令牌,引用%j获取第三个令牌,引用%k获取第三个令牌之后的所有剩余令牌。
你也可以用它来遍历目录、目录内容等等…
Forfiles非常有用,例如,递归删除所有超过两天的文件
forfiles /D -2 /P "C:\Temp" /S /C "cmd /c del @path"
符号链接:
mklink /d directorylink ..\realdirectory
mklink filelink realfile
该命令是Windows Server 2008及更新版本(包括Vista和Windows 7)上的本机命令。(它也包含在一些Windows资源包中。)
cmd.exe本身的/c参数,告诉它运行然后执行这些命令。
我曾经发现自己经常这样做:
win+r, cmd RETURN, ping google.com RETURN
但现在我只知道
win+r, cmd /c ping google.com返回
快得多。如果您正在使用pstools,并且希望使用psexec在远程机器上执行一些命令行功能,那么这也很有帮助。
EDIT: /k工作方式相同,但保持提示打开。这可能经常会派上用场。