Batch to move folders that are 30 days old using F

2019-09-12 15:56发布

I am currently working that moves ONLY folders from one directory to a folder. The current bacth file I have created is as follows.

Set /p target=Select Target Destination:
ForFiles /P "C:\Batch test"  /D -4 /C "CMD /C if @ISDIR==TRUE echo Move @FILE %target%" &Move @File %target%
pause

The problem I have is with using a target directory that has a space in it for instance "C:\Move Test". I was wondering if there was a way to still move folders to another directory that has a space in the name.

2条回答
forever°为你锁心
2楼-- · 2019-09-12 16:27

You can replace the double quotes with their hexadecimal equivalent 0x22:

ForFiles /P "C:\Batch test" /D -4 /C "CMD /C if @ISDIR==TRUE (echo Move @FILE 0x22%target%0x22 & Move @File 0x22%target%0x22)"

If you get problems with other characters you can also replace them; 0x26=&, 0x28=(, 0x29=).

查看更多
看我几分像从前
3楼-- · 2019-09-12 16:30

Your command line looks quite strange, there are several mistakes:

ForFiles /P "C:\Batch test"  /D -4 /C "CMD /C if @ISDIR==TRUE echo Move @FILE %target%" &Move @File %target%

What is wrong:

  • you are talking about 30 days of age, but you specify /D -4, although /D -30 was correct; note that /D checks for the last modification date, not for the creation date!
  • there is an echo in front of the (first) move command, so the move command is displayed rather than executed; to avoid that, simply remove echo;
  • there is a second move command after forfiles, as it appears behind the closing quotation mark of the forfiles /C part, and behind the commmand concatenation operator &; this is completely out of scope of forfiles, therefore @file was treated literally; the ampersand and that orphaned move command needs to be removed;
  • to answer your actual question: to aviod problems with spaces (or other special characters) appearing in file/directory paths, put quotation marks around them; but: since that part appears within the command string after forfiles /C, which is already quoted, you cannot simply use "", you need to escape them; there are two options in forfiles: 1. using \", and 2. using 0x22 (according to the forfiles /? help, you can specify characters by their hexadecimal codes in the format 0xHH, the code 0x22 represents a " character); I strongly recommend option 2., because in variant 1. there still appear " characters that could impact the command interpreter cmd as it is not familiar with the \" escaping (its escape character is ^);

Thus the corrected command line looks like this:

ForFiles /P "C:\Batch test" /D -30 /C "CMD /C if @ISDIR==TRUE Move @FILE 0x22%target%0x22"

For the sake of completeness, this is how option 1. would look like:

ForFiles /P "C:\Batch test" /D -30 /C "CMD /C if @ISDIR==TRUE Move @FILE \"%target%\""

Note that you do not need to quote the source here, because @FILE (like all path-related @-style variables) expand to already quoted strings.

查看更多
登录 后发表回答