DOS Batch File Variable Modifier Returns Blank

2019-09-16 13:15发布

问题:

I have a DOS batch file that will create a report listing files contained within a folder tree. The code below produces the desired output for over 115,000 files. However, 13 records are produced with blank date/time and file size. When I manually execute the DIR command (without the /b option), the desired file information is presented. Can this be corrected without adding considerable workaround code?

FOR /f "tokens=*" %%A IN ('DIR "<Path>" /a:-d /b /s') DO (
  ECHO %%~tA %%~zA %%~dpA %%~nA %%~xA >> test.txt
)

回答1:

(FOR /f "tokens=*" %%A IN ('DIR "<Path>" /a:-d /b /s') DO (
  if exists "%%~A" ECHO %%~tA %%~zA %%~dpA %%~nA %%~xA 
)) >> test.txt

The main reason for not obtaining a date/filesize is that the file can not be found.

How does your code work?

The for /f starts a separate cmd instance that runs the dir command.

When all the data has been retrieved and loaded into memory (that is, the cmd/dir command finished), then the for will start to iterate over the retrieved lines. Some time have passed between the information retrieval and the information processing.

In this time, "maybe" the problematic files have been moved/deleted/renamed and they can no be accessed to retrieve their properties. So, first check if the file still exists

The aditional parenthesis and redirection change are to avoid having to open the target file for each echo operation. This way, the file is opened at the start of the for command and closed at the end.