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

指南:

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

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

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


当前回答

获取当前的日、月和年(独立于locale):

for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)
goto :end_set_date

:set_date
if ("%1:~0,1%" gtr "9") shift
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)
goto :eof

:end_set_date

echo day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%

其他回答

创建并开始编辑一个新文件

copy con new.txt
This is the contents of my file
^Z

Ctrl+Z发送ASCII EOF字符。这就像bash中的heredocs:

cat <<EOF > new.txt
This is the contents of my file
EOF

符号链接:

mklink /d directorylink ..\realdirectory
mklink filelink realfile

该命令是Windows Server 2008及更新版本(包括Vista和Windows 7)上的本机命令。(它也包含在一些Windows资源包中。)

要从文件的第一行开始设置一个环境变量,我使用以下命令:

rem a.txt contains one line: abc123
set /p DATA=<a.txt
echo data: %DATA%

这将输出:abc123

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

使用&::的内联注释。

:: This is my batch file which does stuff.
copy thisstuff thatstuff  &:: We need to make a backup in case we screw up!

:: ... do lots of other stuff

这是如何工作的呢?这是一个丑陋的黑客。&是命令分隔符,大致近似于;UNIX shell。::是另一个丑陋的黑客,有点像REM语句。最终结果是执行命令,然后执行一个什么都不做的命令,从而近似于注释。

这并不是在所有情况下都有效,但它通常足够有用。