2012-08-27 57 views
0

最近我一直在制作这个批处理文件,这使我疯了。批处理文件中的多个IF

我的文件夹结构像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

这里还有多个问题:

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 
+0

非常感谢。为我工作。 这是我的工作代码: @echo off set/p path =输入绝对/相对路径upto root文件夹 FOR/f“tokens = *”%% M in('dir/b“%path%\”' )DO( 如果“%% S”==“web.config”( )对于/ f“tokens = *”%% S in echo%发现web.config )else if“%% S”==“web.bak”( echo Found web.bak )else( rmdir/s/q“%path%\ %% M \ %% S “ 德尔/ F ”%路径%\ %%中号\ %% S“ 回声删除%%小号 ) ) ) 回声已删除所有不需要的内容 暂停 –