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

指南:

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

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

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


当前回答

子例程(输出42):

    @echo off
    call :answer 42
    goto :eof
:do_something
    echo %1
    goto :eof

子例程返回一个值(输出0、1、2,等等):

    @echo off
    setlocal enableextensions enabledelayedexpansion
    call :seq_init seq1
:loop1
    if not %seq1%== 10 (
        call :seq_next seq1
        echo !seq1!
        goto :loop1
    )
    endlocal
    goto :eof

:seq_init
    set /a "%1 = -1"
    goto :eof
:seq_next
    set /a "seq_next_tmp1 = %1"
    set /a "%1 = %seq_next_tmp1% + 1"
    set seq_next_tmp1=
    goto :eof

其他回答

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

> @set fname=%date:/=%

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

还有子字符串……

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

您可以在批处理文件运行时修改它。例如,如果您希望在批处理文件退出之前看到结果,您可以在文件运行时在文件的末尾添加一个被遗忘的暂停。

请参见在批处理文件运行时更改批处理文件

我个人认为这更像是一个陷阱,而不是一个功能。

支持正则表达式的Findstr:

findstr "^[0-9].*" c:\windows\system32\drivers\etc\hosts

我真的很喜欢这个Windows XP命令参考,以及在顶部的语法链接;它涵盖了许多已经在其他答案中找到的技巧和技巧。

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。