I'm trying to write a batch file that iterates through each filename, takes part of the strings, and sets the created and modified dates. Mind you, dirpath is a placeholder for actual path.
@echo off
setlocal enabledelayedexpansion
FOR /R dirpath %F in (*.*) DO (SET FNAME=%~nF SET MM=%FNAME:~0,2% SET DD=%FNAME:~2,2% SET YY=%FNAME:~4,2% nircmd.exe setfiletime %F "%DD% %MM%-20%YY% 00:00:00" "%DD%-%MM%-20%YY% 00:00:00")
I'm not sure how to even troubleshoot what the script is doing - pause doesn't pause the program after the loop. How can this be rewritten to function?
Answer
How can this be rewritten to function?
You have a number of problems with your batch file:
- It's not
%f
. You need use%%f
instead.%f
is for a command line, that needs fixing in at least 3 places. - I would put the commands inside the
do ( ... )
on separate lines. - You can put a pause before the closing
)
- You can comment out the first line with
rem
to see what the batch file is doing. - Add
echo
to the payload line withnircmd
. - Remove the
echo
when you think it's working. - You need in some places to use
!
instead of%
inside thefor
loop (that's whatenabledelayedexpansion
is for - it enables variables to be expanded at execution time rather than at parse time
Start with the following batch file (I've fixed the main mistakes for you):
@echo off
setlocal enabledelayedexpansion
for /r dirpath %%F in (*.*) DO (
set FNAME=%%~nF
SET MM=!FNAME:~0,2!
SET DD=!FNAME:~2,2!
SET YY=!FNAME:~4,2!
echo nircmd.exe setfiletime %%F "!DD!-!MM!-20!YY! 00:00:00" "!DD!-!MM!-20!YY! 00:00:00"
pause
)
endlocal
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
- for /r - Loop through files (Recurse subfolders).
- set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
- setlocal - Set options to control the visibility of environment variables in a batch file.
No comments:
Post a Comment