如何在FOR / R循环中排除Windows目录?

时间:2019-05-16 07:25:42

标签: batch-file

我想回显驱动器C:中的所有文件,但不回显Windows目录中的文件。我可以用for /F来做,但是不能用for /R来做。

问题是for /F太慢而无法回显文件,而for /R却很快。

for /F "tokens=* delims= " %%a in ('dir /b /s c:\*.* ^| find /V "C:\Windows\" ')

上面的代码有效,但是在C驱动器中回显文件大约需要一个小时,因为它等待dir的结果,然后使用find命令对其进行过滤。

我用for /R尝试了打击代码,但没有过滤Windows目录。

for /r "c:\" %%a in (* ^| find /V "C:\Windows\" ')

for /r之后,我还尝试了一些代码来过滤Windows目录:

for /R (*) do ( echo %%A | findstr /v "C:\windows" > null)

但是它很慢,像for /F

我想要一种解决方案以递归方式快速回显所有文件,而不是Windows目录中的文件。

3 个答案:

答案 0 :(得分:1)

当您只想排除根搜索路径中的文件夹时,您可以使用嵌套的 for 循环

@echo off
cd /d C:\

rem Recursively list files inside subfolders, excluding "Windows"
for /d %%d in (*) do (
    if /i not "%%d"=="windows" (
        echo %%d
        dir /b /s "%%d"
    )
)

rem Print the remaining files
dir /b /a:-d

答案 1 :(得分:0)

以下注释的批处理文件代码可用于输出驱动器C:除Windows文件夹之外的所有非隐藏文件的全限定文件名(如果Windows文件夹位于驱动器C:)。

还可以使用除C:以外的任何其他文件夹(作为基础文件夹)作为参数传递给批处理文件来运行该批处理文件。

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "BaseFolder=C:\"
if not "%~1" == "" set "BaseFolder=%~1"
if not "%BaseFolder:~-1%" == "\" set "BaseFolder=%BaseFolder%\"

setlocal EnableDelayedExpansion
if not "!BaseFolder:%SystemRoot%\=!" == "%BaseFolder%" (
    endlocal
    endlocal
    echo Searching in any Windows folder is not done by %~nx0.
    echo/
    pause
    goto EndBatch
)
endlocal

rem Output non-hidden files in base folder.
for %%I in ("%BaseFolder%*") do echo %%I

rem For each folder in base folder except always ignored Windows folder
rem call the subroutine ProcessFolder with full qualified folder name.
for /D %%I in ("%BaseFolder%*") do if /I not "%%I" == "%SystemRoot%" call :ProcessFolder "%%I"

endlocal
goto EndBatch

rem The subroutine ProcessFolder runs a recursive search for all
rem non-hidden files in all folders (including hidden folders)
rem and outputs the full qualified names of all found files.
:ProcessFolder
for /R "%~1" %%J in (*) do echo %%J
goto :EOF

:EndBatch

要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。

  • call /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?

答案 2 :(得分:0)

我同意dbenham的评论,因为您完全不需要For循环即可完成此任务。

我可能会建议:

Dir /B/S/A-D C:\*|Find /I /V "C:\Windows\"

或使用系统变量:

Dir /B/S/A-D %SystemDrive%\*|Find /I /V "%SystemRoot%\"

如果您希望将输出保存在文件中以方便阅读/检查,请注意,如果将输出文件放在同一驱动器中,则可能会将其包含在其自己的结果中。

相关问题