Forfiles Batch Script (Escaping @ character)

This an old question but I've got a different answer... in case anyone needs it.

When using 'forfiles', the path (written after /p) CAN be between quotation marks. However, it must not end with a slash.

If you want to run 'forfiles' for the root directory of a drive:
forfiles /p "C:" /c "cmd /c echo @file"

If you want to process files in a different directory...
forfiles /p "C:\Program Files" /c "cmd /c echo @file"

In other words, the safest approach is:

  • Always use quotation marks (because folders with spaces, like 'Program Files', will still work)
  • Always omit the last trailing slash

forfiles /p "C:\Path\Without\Trailing\Slash"


I had the same problem until I removed the quotation marks around the directory path , like this:

forfiles /S /P r:\ /m *.bak /d -10 /c "cmd /c echo @PATH"

Hope that helps.


Try trimming the trailing \ from your /P path. Then you should be able to use quotes to encapsulate a path that includes a space.


Best practice would be to use double-quote marks around the path (/P) parameter to handle paths with spaces.

The issue occurs when the substitution variable contains a trailing backslash. The backslash 'escapes' the quote, causing FORFILES to mis-interpret the rest of the command line.

By convention, the path to a directory does not need the trailing backslash, the one exception to this being the root directory. Specifying only the drive letter and a colon C: does NOT refer to the root - rather it refers to the 'current directory' for that drive. To refer to the root, one must use the trailing backslash C:\.

My solution is as follows:

When using FORFILES, append a . prior to the closing " of the /P parameter e.g.

FORFILES /P "%somePath%." /C "CMD /C ECHO @path"

After substitution, this leads to paths of the form C:\.,C:\TEMP. or C:\TEMP\.. All of these are treated correctly by FORFILES and also DIR.

I have not tested all the possible FORFILES substitution variables but @path appears to be unaffected by the addition of the .