在批处理文件中使用 endlocal 设置变量,但变量在 setlocal/endlocal 块之外永远不可用

Using endlocal set variables in a batch file, but the variables are never available outside of the setlocal/endlocal block

我正在尝试设置 SETLOCAL 内部、FOR 循环内部和 IF 语句内部的变量值。但是,它似乎永远不会起作用。我尝试在 ENDLOCAL 语句中使用 SET 语句,但这似乎并没有实际设置任何内容。回显之后的变量只回显原来的设定值0.

@ECHO off

SET pathsource=K:
SET sourcefile=0
SET counter=0

SETLOCAL enableextensions enabledelayedexpansion

REM Get the newest pptx file in the specified directory. Get the filename and last modified timestamp
FOR /f "tokens=1-3,5*" %%a IN ('dir ^"%pathsource%\*.pptx^" /a-d-h-s /o-d /tw ^| find /i ^".pptx^"') DO (
    REM echo !counter!

    REM only get the first row by using a counter
    IF !counter! EQU 0 (
        REM variables are: a-date, b-time, c-am/pm, d&e-filename
        ECHO %%a %%b %%c %%d %%e

        SET sourcefile=%%d %%e
    )

    SET /A counter+=1
)


ENDLOCAL & (
    SET "sourcefile=%sourcefile%"
)

ECHO %sourcefile%

REM do other stuff with the %sourcefile% variable after this

因为您在 Set/End 本地块中分配值,一旦达到 ENDLOCAL 命令,在此块中所做的任何更改都将被丢弃。

只需将 SETLOCALENDLOCAL 命令分别移动到脚本的最顶部和底部。这将使整个脚本中的所有分配都贯穿始终。


此外,您实际上并不需要计数器变量。处理完第一个文件就可以直接跳出循环:

@ECHO off
REM delayed expansion not needed for the portion shown
SETLOCAL enableextensions

SET pathsource=K:
SET sourcefile=0

REM Get the newest pptx file in the specified directory. Get the filename and last modified timestamp
FOR /f "tokens=1-3,5*" %%a IN ('dir ^"%pathsource%\*.pptx^" /a-d-h-s /o-d /tw ^| find /i ^".pptx^"') DO (
    REM variables are: a-date, b-time, c-am/pm, d&e-filename
    ECHO %%a %%b %%c %%d %%e

    SET sourcefile=%%d %%e

    REM We only care about the first row
    GOTO EndLoop
)

:EndLoop
ECHO %sourcefile%

REM do other stuff with the %sourcefile% variable after this

ENDLOCAL

最后一件事是您可以使用本机 DIRFOR 变量命令稍微简化 FOR 语法:

@ECHO off
REM delayed expansion not needed for the portion shown
SETLOCAL enableextensions

SET pathsource=K:
SET sourcefile=0

REM Get the newest pptx file in the specified directory. Get the filename and last modified timestamp
CD "%pathsource%\"
FOR /f "usebackq tokens=* delims=" %%a IN (`dir "%pathsource%\*.pptx" /a-d-h-s /o-d /tw /b`) DO (
    REM Use For loop variables.
    REM Print the date/time and file name.
    ECHO %%~ta %%~a

    SET sourcefile=%%~a

    REM We only care about the first row
    GOTO EndLoop
)

:EndLoop
ECHO %sourcefile%

REM do other stuff with the %sourcefile% variable after this

ENDLOCAL

如果您只需要最新的 PPTX 文件的名称和时间戳,那么您的脚本比需要的要复杂得多。简单地抓取 dir "path\*.pptx" /b /o:-d 然后在第一行之后跳出 for /f 循环。

@ECHO off
setlocal

SET "pathsource=K:"

REM Get the newest pptx file in the specified directory. Get the filename and last modified timestamp
pushd "%pathsource%"
FOR /f "delims=" %%a IN ('dir "*.pptx" /b /o:-d') DO (
    set "sourcefile=%%~nxa"
    set "timestamp=%%~ta"
    goto break
)
:break

ECHO %sourcefile%
echo %timestamp%

REM do other stuff with the %sourcefile% variable after this