- 1 year ago
Batch file variable filenames: make timestamp filename within a for loop?
To create a timestamped filename within a batch file's for
loop, you can use the %DATE%
and %TIME%
environment variables to extract the current date and time. However, these variables may contain characters that are not allowed in filenames, such as slashes and colons. Therefore, you need to modify the timestamp format to make it suitable for a filename.
Here's an example of how you can create a timestamped filename within a for
loop in a batch file:
batch@echo off
setlocal
REM Get current date and time
set "timestamp=%DATE:/=_%%TIME::=_%"
set "timestamp=%timestamp: =%"
set "timestamp=%timestamp:.=%"
REM Iterate over files in a directory
for %%F in (C:\path\to\files\*) do (
REM Create timestamped filename
set "filename=%%~nF_%timestamp%%%~xF"
REM Process the file or do something with the filename
echo Filename: %filename%
)
In this example, the %DATE%
and %TIME%
variables are modified to remove characters that are not allowed in filenames. The resulting timestamp is then appended to the original filename using an underscore _
as a separator. Adjust the path and file pattern in the for
loop to match your specific requirements.
Note that the resulting filename may still contain other characters that are not allowed in filenames on certain file systems. Make sure to sanitize the filename further if needed to ensure compatibility with your target file system.