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

指南:

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

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

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


当前回答

具有数值变量的循环的正确格式是

for /l %%i in (startNumber, counter, endNumber) do echo %%i

更多详情> http://www.ss64.com/nt/for.html

其他回答

就像上面一样,使用CALL, EXIT /B, SETLOCAL和ENDLOCAL,你可以用局部变量和返回值来实现函数。

例子:

@echo off

set x=xxxxx
call :fun 10
echo "%x%"
echo "%y%"
exit /b

:fun
setlocal
set /a y=%1 + 1
endlocal & set x=%y%
exit /b

这将打印:

"11"
""

y变量永远不会离开局部作用域,但由于CMD一次解析一行的方式,您可以将值提取到父作用域的x变量中。

There is also the EDLIN command. While it may be an old bastard tool once used for line-based text editing, the fact that it's controllable from the command line makes it rather useful for batch scripting, mostly because, just like any other case you'd be using EDLIN, it's the only tool available. After all, EDLIN is not a tool you would ordinarily want to use for text editing, unless you are somewhat masochistic. To quote Tim Patterson (the fellow who wrote it): "I was aghast when I heard that IBM was using it and not throwing it out the window."

注意:EDLIN将老式的EOF (1A)标记添加到它编辑的文件中。如果需要删除它们,可能必须使用DEBUG。

Forfiles非常有用,例如,递归删除所有超过两天的文件

forfiles /D -2 /P "C:\Temp" /S /C "cmd /c del @path"

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

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:\>

列出所有驱动器:

fsutil fsinfo drives