Forfiles Batch Script (Escaping @ character)

后端 未结 8 941
闹比i
闹比i 2020-12-15 05:35

I\'m working on a batch script that will let me delete files older then a set period using forfiles. For now, I\'m aiming at printing the files that will be deleted.

8条回答
  •  离开以前
    2020-12-15 06:32

    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 varialble 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, be @path appears to be unaffected by the addition of the .

提交回复
热议问题