Search code examples
windowsbatch-fileforfiles

Why is Forfiles recursing even though I'm not using the /S parameter?


In my Windows batch file on Windows Server 2008 R2 Standard, I'm trying to use the Forfiles command without recursing through my files, but it still recurses even though I am not using the /S parameter.

How can I get it to stop recursing

I've tried it with both @path and @file and even with the /s. When I use the /S, the amount of recursion is ridiculous!

ForFiles /p "C:\temp" /d -30 /c "cmd /c dir @path" >temp.txt

In the code above, I expect the temp.txt to only show files in the specified folder, not any of it's subfolders.


Solution

  • Let's consider what you are asking the system to do:

    Forfiles /p "C:\temp" /d -30
    

    The above command does pretty much what you intended, find any file/folder older than 30 days.

    /c "cmd /c dir @path"
    

    This does not do what you think. You are effectively asking cmd to dir each match found by forfiles and do the full dir of each @path, including folders. So let's say you have a dir older than 30 days:

    C:\Temp\oldInstalldir\
    

    You are telling cmd.exe to do:

    dir "C:\Temp\oldinstalldir"
    

    as well as dir for each file in c:\temp again. So what you really want is to list the files you found older than 30 days which forfiles already found for you, so a working solution is to just echo them.

    ForFiles /p "C:\temp" /d -30 /c "cmd /c echo @path">temp.txt
    

    Or by filename only (no path):

    ForFiles /p "C:\temp" /d -30 /c "cmd /c echo @file">temp.txt