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

时间:2015-01-29 16:50:23

标签: batch-file

我试图设置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

2 个答案:

答案 0 :(得分:3)

由于您在Set / End Local块中分配了值,因此在达到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

最后一件事是,您可以使用原生FORDIR变量命令简单地使用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

答案 1 :(得分:0)

如果你想要的只是最新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