批处理文件(ForFiles用于逻辑的多个条件命令)?

时间:2015-07-10 17:16:32

标签: batch-file command

我刚刚进入Bat文件。 我试图删除网络共享驱动器上的旧文件夹,但按名称跳过2个包含的文件夹。 基本上我需要我每天制作的所有文件,并始终保留2个旧文件。

删除所有超过3天的文件的代码:

PushD "\\****-****\build" &&(
ForFiles /D -3 /C "CMD /C if @ISDIR==TRUE  echo RD @FILE &RD /S @FILE
 ) & PopD

我正在考虑这样的事情:如果不是@FNAME ==%name%。我不完全理解这个过程,我能在forFiles中有两个条件吗?以前我必须要/ c吗?

PushD "\\****-****\build" &&(
ForFiles /D -3 /C "CMD /C if NOT @FNAME == %name% if @ISDIR==TRUE  echo RD @FILE &RD /S @FILE
 ) & PopD

我似乎无法得到它,你介意帮助我吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

它有点乱,但我能够在本地目录上进行:

 @echo off

mkdir Temp\Temp

REM Copy all old file to Temp dir
forfiles -p "%cd%"  -m *.* /D -2 /C "cmd /c xcopy @path %cd%\Temp"

REM copy a random file from Temp dir to Temp/Temp dir and then delete it
FOR %%A in (%cd%\Temp\*) do (
   COPY "%%A"  %cd%\Temp\Temp\
   DEL "%%A"
   GOTO :Second
)
:Second

Rem copy second random file from Temp dir
FOR %%A in (%cd%\Temp\*) do (
   COPY "%%A"  %cd%\Temp\Temp\
   GOTO :Del
)
:Del

Rem delete all old files from local dir
forfiles -p "%cd%"  -m *.* /D -2 /C "cmd /c del @path"

Rem Copy back two random old files to local dir
xcopy %cd%\Temp\Temp\* %cd%

Rem remove Temp dir
rmdir /s /q Temp

答案 1 :(得分:1)

是的,在{em>然后分支中嵌套if命令是如何拥有逻辑AND的方式。请注意下一个代码段中的正确引用:

@ECHO ON >NUL
@SETLOCAL enableextensions
set "name=SO"
set "nam2=SU"
pushd "D:\VB_scripts"
@rem all directories 
ForFiles /D -2 /C "CMD /C if @ISDIR==TRUE echo @FILE"
@rem all directories except "SO" 
ForFiles /D -2 /C "CMD /C if @ISDIR==TRUE if not @FNAME=="""%name%""" echo @FILE"
@rem all directories except "SO" and "SU" 
ForFiles /D -2 /C "CMD /C if @ISDIR==TRUE if not @FNAME=="""%name%""" if not @FNAME=="""%nam2%""" echo @FILE"
popd
@ENDLOCAL

<强>输出

==>D:\bat\SO\31346676.bat

==>set "name=SO"

==>set "nam2=SU"

==>pushd "D:\VB_scripts"

==>ForFiles /D -2 /C "CMD /C if @ISDIR==TRUE echo @FILE"

"Class Pack"
"Oldies"
"SO"
"SU"
"WMI"

==>ForFiles /D -2 /C "CMD /C if @ISDIR==TRUE if not @FNAME=="""SO""" echo @FILE"

"Class Pack"
"Oldies"
"SU"
"WMI"

==>ForFiles /D -2 /C "CMD /C if @ISDIR==TRUE if not @FNAME=="""SO""" if not @FNAME=="
""SU""" echo @FILE"

"Class Pack"
"Oldies"
"WMI"

==>popd