【问题标题】:Batch script, checking if folder exists fails inside loop批处理脚本,检查文件夹是否存在在循环内失败
【发布时间】:2021-07-11 22:26:57
【问题描述】:

我正在尝试检查是否存在多个目录,其中包含一个批处理文件,在一个循环中,但它失败了。 逻辑可能看起来有点奇怪,但我需要像其他处理那样的参数,为了简单起见,我从脚本中省略了这些参数。

@ECHO OFF
SET output_path=C:\Users\test\Desktop\

SET scenario[0].param1=15
SET scenario[0].param2=100
SET scenario[0].param3=3600
SET scenario[1].param1=10
SET scenario[1].param2=1000
SET scenario[1].param3=3600

SET "i=0"

:CaseLoop
IF DEFINED scenario[%i%].param1 IF DEFINED scenario[%i%].param2 IF DEFINED scenario[%i%].param3 (

SET cur.param1=
SET cur.param2=
SET cur.param3=
FOR /f "delims==. tokens=1-3" %%j in ('SET scenario[%i%]') do (
  SET cur.%%k=%%l
)

REM Check if output directory exists
CALL ECHO "%%output_path%%\%%cur.param1%%-%%cur.param2%%-%%cur.param3%%\"
IF EXIST "%%output_path%%\%%cur.param1%%-%%cur.param2%%-%%cur.param3%%\" (
  CALL ECHO SUCCESS
) ELSE (
  CALL ECHO NO
)
SET /a "i+=1"
GOTO :CaseLoop
)

目录确实存在,但由于某种原因它进入了 else 语句。 我认为这可能是变量扩展,但在 ECHO 回声之前的行中 C:\Users\test\Desktop\15-100-3600\C:\Users\test\Desktop\10-1000-3600\ 分别

【问题讨论】:

  • 原因是%%被解释为书面%的转义,所以它实际上检查`%output_path%\%cur.param1%-%cur.param2%- %cur.param3%`
  • 它在证明之前输出正确的行,因为你使用call echo,但是你可以只使用echo,用一个%代替%%
  • 我最好的选择可能是SETLOCAL EnableDelayedExpansion 并使用IF EXIST "%output_path%\!cur.param1!-!cur.param2!-!cur.param3!\"
  • 是的,@znaya,因为call if 不起作用……

标签: loops if-statement batch-file


【解决方案1】:

你为什么不直接改变方法,而不是将代码的主要部分包含在IF DEFINED括号中的块中,绕过相反场景的代码IF NOT DEFINED

例子:

@Echo Off
SetLocal EnableExtensions
Set "output_path=C:\Users\test\Desktop"
Set /A scenario[0].param1=15, scenario[0].param2=100, scenario[0].param3=3600
Set /A scenario[1].param1=10, scenario[1].param2=1000, scenario[1].param3=3600
Set "i=0"

:CaseLoop
For /L %%G In (1,1,3) Do If Not Defined scenario[%i%].param%%G (GoTo :Next) Else Set "cur.param%%G="
For /F "Tokens=2,* Delims==." %%G In ('Set scenario[%i%]') Do Set "cur.%%H=%%I"
Rem Check if output directory exists
Echo "%output_path%\%cur.param1%-%cur.param2%-%cur.param3%"
If Exist "%output_path%\%cur.param1%-%cur.param2%-%cur.param3%\" (Echo SUCCESS) Else Echo NO
Set /A i += 1
GoTo CaseLoop

:Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 2018-12-08
    • 2013-04-27
    相关资源
    最近更新 更多