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

指南:

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

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

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


当前回答

设置环境变量时的搜索和替换:

> @set fname=%date:/=%

...从日期中删除“/”以用于带时间戳的文件名。

还有子字符串……

> @set dayofweek=%fname:~0,3%

其他回答

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

使用SET /P从文件中设置环境变量

SET /P SVNVERSION=<ver.tmp

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

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

删除周围的报价。

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

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

要获取当前日期/时间用于日志文件等,我在批处理文件中使用这个:

for /f "usebackq tokens=1,2,3,4,5,6,7 delims=/:. " %%a in (`echo %DATE% %TIME%`) do set NOW=%%d%%b%%c_%%e%%f%%g
set LOG=output_%NOW%.log