批处理文件中的多个IF

时间:2012-08-27 10:04:38

标签: batch-file

最近我一直在制作这个批处理文件,这让我疯狂。

我的文件夹结构类似于C:\ MainFolder \ Dir \,“Dir”包含许多子文件夹和文件。 在这些子文件夹中有许多文件和子文件夹,包括2个文件“C.txt”和“D.txt” 我的任务是删除这些子文件夹中的所有其他内容,并仅保留这两个文件。但它没有用。 请帮助。

我的代码是:

@echo off
FOR /f "tokens=*" %%M in ('dir /b "C:\MainFolder\Dir\"') DO (
For /f "tokens=*" %%S in ('dir /b "C:\MainFolder\Dir\%%M"') DO ( 
if "%%S"=="C.txt" ( 
echo Found C
) 
else if "%%S"=="D.txt" ( 
echo Found D
) 
else (
::Code to delete the file Or Directory
echo Deleted %%S
)

)
)
echo Deleted Unwanted Content
pause

1 个答案:

答案 0 :(得分:1)

这里有很多问题:

else必须与(

显示在同一行
if "%%S"=="C.txt" ( 
  echo Found C
) else if "%%S"=="D.txt" ( 
  echo Found D
) else (
  ::Code to delete the file Or Directory
  echo Deleted %%S
)

不要将::用于评论,它会在某些地方中断。请改用rem

) else (
  REM Code to delete the file Or Directory
  echo Deleted %%S
)

请缩进你的代码。它让阅读更加愉快:

@echo off
FOR /f "tokens=*" %%M in ('dir /b "C:\MainFolder\Dir\"') DO (
  For /f "tokens=*" %%S in ('dir /b "C:\MainFolder\Dir\%%M"') DO ( 
    if "%%S"=="C.txt" ( 
      echo Found C
    ) else if "%%S"=="D.txt" ( 
      echo Found D
    ) else (
      REM Code to delete the file Or Directory
      echo Deleted %%S
    )
  )
)
echo Deleted Unwanted Content
pause