问题
Using Windows batch, this function returns creation dates of a file:
:creationDate
set "CompareFile=%~1"
echo !CompareFile!
for /f "skip=5 tokens=1,2,4,5* delims= " %%a in ('dir /a:-d /o:d /t:c') do (
if "%%~c" NEQ "bytes" (
if "%%~d"=="!CompareFile!" ( set "%~2=%%~a %%~b" )
)
)
goto:eof
Example usage:
call :creationDate "!MyFile!" MyFileCreationDate
echo !MyFile! was made on !MyFileCreationDate!
The Variables in the function:
%%~a = Creation Date
%%~b = Creation Time
%%~d = Filename (error when there is spaces!)
%%~1 = Filename to get the creation date for
%%~2 = Variable to store creation date in
But it does not work on filenames with spaces or special characters. In that case %%~d maybe will contain just the first few letters of the filename, or nothing, resulting in no value being returned to argument 2
The goal is to get it to match to a filename w/ spaces I've passed to a subroutine as argument 1 and return argument 2 as the creation date of argument 1.
回答1:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=."
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*.txt" '
) DO (
CALL :creationdate "%sourcedir%\%%a" c crdatetime
CALL :creationdate "%sourcedir%\%%a" w wrdatetime
CALL :creationdate "%sourcedir%\%%a" a acdatetime
ECHO !crdatetime! !wrdatetime! !acdatetime! %%a
)
GOTO :EOF
:creationDate
for /f "skip=5 tokens=1,2 delims= " %%a in (
'dir /a:-d /o:d /t:%2 "%~1"') do set "%~3=%%~a %%~b"&goto:eof
goto:eof
Although I'd change the name of the routine.
回答2:
- Why don't you include the file name in the dir command?
- To exclude other lines of the dir you could pipe to a findstr.
:: Q:\Test\2017-04\30\SO_43708547.cmd
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Set "MyFile=%~1"
call :creationDate "!MyFile!" MyFileCreationDate
echo !MyFile! was made on !MyFileCreationDate!
Goto :Eof
:creationDate
for /f "tokens=1-3* delims= " %%a in (
'dir /a:-d /o:d /t:c "%~1" ^| findstr /i "%~nx1$" '
) do set "%~2=%%~a %%~b"
goto:eof
Sample output (with my user settings date format):
> SO_43708547.cmd "test name.txt"
test name.txt was made on 2017-04-30 18:49
Edit Changed test file to include a space.
来源:https://stackoverflow.com/questions/43708547/creation-date-in-windows-cmd