gpt4 book ai didi

batch-file - 在批处理文件中使用 endlocal 设置变量,但这些变量在 setlocal/endlocal block 之外永远不可用

转载 作者:行者123 更新时间:2023-12-03 09:55:00 31 4
gpt4 key购买 nike

我正在尝试设置 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 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

最后一件事是您可以简单地使用您的 FOR使用 native 的语法 DIRFOR变量命令:
@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

关于batch-file - 在批处理文件中使用 endlocal 设置变量,但这些变量在 setlocal/endlocal block 之外永远不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28220141/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com