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

指南:

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

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

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


当前回答

通过使用CALL, EXIT /B, SETLOCAL和ENDLOCAL可以实现带有局部变量的子例程。

例子:

@echo off

set x=xxxxx
call :sub 10
echo %x%
exit /b

:sub
setlocal
set /a x=%1 + 1
echo %x%
endlocal
exit /b

这将打印

11
xxxxx

尽管:sub修改了x。

其他回答

搜索路径上的可执行文件(或其他类似路径的字符串,如果需要):

c:\> for %i in (cmd.exe) do @echo. %~$PATH:i
C:\WINDOWS\system32\cmd.exe

c:\> for %i in (python.exe) do @echo. %~$PATH:i
C:\Python25\python.exe

c:\>

获取当前的日、月和年(独立于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%

递归搜索目录树中的字符串:

findstr /S /C:"string literal" *.*

你也可以使用正则表达式:

findstr /S /R "^ERROR" *.log

递归文件搜索:

dir /S myfile.txt

我使用它们作为常用目录的快捷方式。 一个名为“sandbox.bat”的示例文件,它位于我的PATH目录中

EXPLORER "C:\Documents and Settings\myusername\Desktop\sandbox"

调用脚本只需WIN+R—>沙盒

符号链接:

mklink /d directorylink ..\realdirectory
mklink filelink realfile

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