0

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

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

我的代码是:

@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
4

1 回答 1

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
于 2012-08-27T10:46:14.010 回答