Creating files and folders with names based on the current date and time is a crucial aspect of organizing data, automating backups, and logging in Windows environments. Windows Batch Script, the scripting language for Windows Command Prompt, offers straightforward methods to incorporate date and time stamps into your filenames and directory names. This article explores how to achieve this, ensuring your scripts can dynamically generate unique and descriptive names.
Understanding Windows Batch Script Date & Time
In Windows Batch Script, the %DATE% and %TIME% environment variables provide the current date and time, respectively. However, their format is influenced by the system’s regional settings, which can vary. Typically, %DATE% returns the date in the format “Fri 03/01/2024“, and %TIME% provides the time in the format “12:30:45.78”.
Formatting Date and Time
To create file or folder names with date and time, you must extract and format these values accordingly. Since direct formatting options like in Linux’s date command are not available, you’ll often need to use substring extraction and replacement techniques.
Extracting Date Components
Here’s how you can extract year, month, and day from the %DATE% variable, assuming the format is MM/DD/YYYY:
set YEAR=%DATE:~10,4%
set MONTH=%DATE:~4,2%
set DAY=%DATE:~7,2%
Extracting Time Components
Similarly, to extract hour, minute, and second from %TIME%, you might use:
set HOUR=%TIME:~0,2%
set MINUTE=%TIME:~3,2%
set SECOND=%TIME:~6,2%
Generating Names Based on Date and Time
With the date and time components extracted, you can now combine them to form unique file or folder names.
Creating a Timestamped File Name
set FILENAME=Log_%YEAR%-%MONTH%-%DAY%_%HOUR%-%MINUTE%-%SECOND%.txt
echo Log entry > %FILENAME%
This script creates a log file named like Log_2024-03-01_12-30-45.txt.
Creating a Directory Based on the Date
For organizing backups or logs by date, you might create a directory like so:
set DIRNAME=Backup_%YEAR%-%MONTH%-%DAY%
mkdir %DIRNAME%
This command creates a directory named Backup_2024-03-01.
Handling Single-Digit Day and Month
One challenge is that single-digit months and days can lead to names with unexpected formats due to leading spaces. To ensure a consistent two-digit format, you can add a zero padding where necessary:
if %MONTH% LSS 10 set MONTH=0%MONTH:~1,1%
if %DAY% LSS 10 set DAY=0%DAY:~1,1%
To utilize the script in a Windows environment for generating timestamped filenames and directory names, follow these steps: Create a new file named script.bat and input the content outlined below. This script is designed to extract the current date and time, format these elements for consistency, and then employ them to construct a unique log file and a backup directory.
@echo off
:: Extract year, month, and day from the system's date
set YEAR=%DATE:~10,4%
set MONTH=%DATE:~4,2%
set DAY=%DATE:~7,2%
:: Ensure month and day are two digits (add leading zero if necessary)
if %MONTH% LSS 10 set MONTH=0%MONTH:~1,1%
if %DAY% LSS 10 set DAY=0%DAY:~1,1%
:: Extract hour, minute, and second from the system's time
set HOUR=%TIME:~0,2%
set MINUTE=%TIME:~3,2%
set SECOND=%TIME:~6,2%
:: Ensure hour, minute, and second are two digits (add leading zero if necessary)
if %HOUR% LSS 10 set HOUR=0%HOUR:~1,1%
if %MINUTE% LSS 10 set MINUTE=0%MINUTE:~1,1%
if %SECOND% LSS 10 set SECOND=0%SECOND:~1,1%
:: Create a log file with the current timestamp in its name
set FILENAME=Log_%YEAR%-%MONTH%-%DAY%_%HOUR%-%MINUTE%-%SECOND%.txt
echo Log entry > %FILENAME%
:: Create a directory with the current timestamp in its name
set DIRNAME=Backup_%YEAR%-%MONTH%-%DAY%
mkdir %DIRNAME%
After saving the script as script.bat, you can run it by double-clicking the file or executing it from the command prompt.
You will find that a directory is created with the name “Backup_2024-03-02”. Also, a file created in the current directory with the name “Log_2024-03-02_07-02-07.txt” (Filename will be according to current date and time and will change during your testing)
Conclusion
Generating file and folder names based on the current date and time in Windows Batch Script requires a bit more manual effort compared to other scripting environments. However, by extracting and formatting date and time components, you can create meaningful, unique names for files and directories. This approach is invaluable for automated data management tasks, ensuring your scripts can handle files in an organized, chronological manner.
I created this script for use in my AutoBootVHD8.cmd file which is part of a hands on lab http://ITProGuru.com/HOL
Here is the resulting code..
@echo Backing up Boot Configuration Data
Rem Create FileName with datatime
:: this is Regional settings dependent so tweak this according your current settings
Echo %DATE% %Time%
for /f “tokens=1-8 delims=::./ ” %%A in (‘echo %DATE% %TIME%’) do set FileDateTime=%%D%%C%%B-%%E%%F%%G
ECHO FileDateTime IS %FileDateTime%
@echo %temp%AutoBootBackup-%filedatetime%.bak
Echo This is a test file > %temp%AutoBootBackupTemp-%FileDateTime%.bak
BCDEDIT /export %temp%AutoBootBackup-%FileDateTime%.bak
dir %temp%AutoBootBackup*
Now, I will explain what each line does
Command | Description |
@echo Backing up Boot Configuration Data | Display a comment on the screen so the user knows what we are doing |
Rem Create FileName with datatime | Code comment that just tells other programmers that are looking at the code what we are doing. |
:: this is Regional settings dependent so tweak this according your current settings | Another comment, just a note to programmers |
Echo %DATE% %Time% | This is used to DISPLAY the contents of what we will be parsing. You do not need to leave it in the code. I left it in so you could easily tweak for different regional settings or rearranging the values. The output of this is used to figure out what the different parts are in our loop Output: Thu 02/07/2013 10:53:06.12 |
for /f “tokens=1-8 delims=::./ ” %%A in (‘echo %DATE% %TIME%’) do set FileDateTime=%%D%%C%%B-%%E%%F%%G | This is where all the real work is done. We are looping through the output of the “%DATE% %Time%” output and breaking it down into different parts (called tokens).
in (‘echo %DATE% %TIME%’) tells the script to process the results of this statement for the text we are going to scan through. The output can be seen above. Tokens are defined by “tokens=1-8 delims=::./ ” 1-8 says return only the first through the 8th tokens. A token is a Part. tokens are defined by a character which is defined by the %%A which says starting with “A” return each token in the next ASCII character. So A=Token1, B=Token2, C=Token3, etc all the way up to the max tokens which in this statement is 8 (remember 1-8 tokens) In this case, we are using several “delims” (delimiters). delims are defined by delims=::./ “ Anytime one of these characters is found in the string we are processing a new token will be created from the text “Thu 02/07/2013 10:53:06.12” After the tokens are broken up they are stored in variables %%A through %%H So the last thing we have to do is create a new variable that uses our tokens to create the FileDateTime variable. This is done with the part of the statement “do set FileDateTime=%%D%%C%%B-%%E%%F%%G” In my case, I am not using the %%H variable and I rearranged the date tokens so it would display YYYYMMDD followed by the time HHMMSS and I store that into a new variable called FileDateTime |
ECHO FileDateTime IS %FileDateTime% | display the contents of our new variable FileDateTime
Output: FileDateTime IS 20130702-105306 |
@echo %temp%AutoBootBackup-%filedatetime%.bak | Now use this FileDateTime variable to display what we will be using for our actual filename. The %temp% is a variable that is the location of Temporary files Output: C:UsersDSTOLT~1.NORAppDataLocalTempAutoBootBackup-20130702-105306.bak |
Echo This is a test file > %temp%AutoBootBackupTemp-%FileDateTime%.bak | This command just creates a temporary text file using the temp variable and the FileDateTime variable with a .bak extention. The contents of the text file is “This is a test file” and the name of the file is:
C:UsersDSTOLT~1.NORAppDataLocalTempAutoBootBackupTemp-20130702-105306.bak |
BCDEDIT /export %temp%AutoBootBackup-%FileDateTime%.bak | You can delete this line. This is how I will ultimately be using the command. I am passing the output filename to the BCDEDIT /Export function. |
dir %temp%AutoBootBackup* | I am just showing a listing of the files in my temp folder that start with “AutoBootBackup” so I can see that the file was successfully created. |
Please NOTE: The only line you really need is the “for /f “tokens=1-8 delims=::./ ” %%A in (‘echo %DATE% %TIME%’) do set FileDateTime=%%D%%C%%B-%%E%%F%%G” This will set an environment variable for FileDateTime then you can use that however you like. All the other lines in the script are simply provided to show you examples of how you can use this technology.
output from running the script on my computer:
C:Boot>filedatetime
Backing up Boot Configuration Data
C:Boot>Rem Create FileName with datatime
C:Boot>Echo Thu 02/07/2013 10:53:06.12
Thu 02/07/2013 10:53:06.12
C:Boot>for /F “tokens=1-8 delims=::./ ” %A in (‘echo Thu 02/07/2013 10:53:06.12
‘) do set FileDateTime=%D%C%B-%E%F%G
C:Boot>set FileDateTime=20130702-105306
C:Boot>ECHO FileDateTime IS 20130702-105306
FileDateTime IS 20130702-105306
C:UsersDSTOLT~1.NORAppDataLocalTempAutoBootBackup-20130702-105306.bak
C:Boot>Echo This is a test file 1>C:UsersDSTOLT~1.NORAppDataLocalTempAutoBootBackupTemp-20130702-105306.bak
C:Boot>BCDEDIT /export C:UsersDSTOLT~1.NORAppDataLocalTempAutoBootBackup-20130702-105306.bak
The operation completed successfully.
C:Boot>dir C:UsersDSTOLT~1.NORAppDataLocalTempAutoBootBackup*
Volume in drive C is OSDisk
Volume Serial Number is FE20-0485
Directory of C:UsersDSTOLT~1.NORAppDataLocalTemp
02/07/2013 10:28 AM 65,536 AutoBootBackup-20130702-102855.bak
02/07/2013 10:29 AM 65,536 AutoBootBackup-20130702-102905.bak
02/07/2013 10:47 AM 65,536 AutoBootBackup-20130702-104709.bak
02/07/2013 10:53 AM 65,536 AutoBootBackup-20130702-105306.bak
02/07/2013 10:47 AM 65,536 AutoBootBackup.bak
02/07/2013 10:47 AM 22 AutoBootBackupTemp-20130702-104709.bak
02/07/2013 10:53 AM 22 AutoBootBackupTemp-20130702-105306.bak
7 File(s) 327,724 bytes
0 Dir(s) 174,626,017,280 bytes free
C:Boot>
I do hope you found this helpful. If you did, send me a thank you note with the URL on Twitter @ITProGuru
You can use only the date or only the time by just deleting the parts you do not want from the
do set FileDateTime=%%D%%C%%B-%%E%%F%%G
part of the command
%%D=Year
%%C=Month
%%B=Day
– = Static text
%%E=Hour
%%F=Min
%%G-=Sec
%%H=hundreds of seconds which I did not use
%%A= Day of week which I did not use
If I add another command to the top of the script (@Echo Off) I would get the following (clean) output
One of the very popular and useful tricks with Microsoft Windows is changing the dates and times of your files using Command Prompt (CMD) or PowerShell. This skill is super useful whether you’re an IT pro, someone who manages computer systems, or just someone who loves to organize their files. It helps with sorting files, syncing them up, or even fixing problems.
In this article, we’ll look at how to play around with the dates and timestamps of files using CMD and PowerShell in Windows 11 or Windows 10. Through this guide, you’ll learn how to update these details for both single and multiple files easily.
What are a file’s date and timestamp attributes?
Let’s first understand what the different dates and times are that you might want to change for a file. In Windows, these are the big three:
- The date when the file first came into being.
- The date when the file last got an update or save.
- The date when someone last opened or peeked at the file.
These bits of info are stored with your files and can be modified as needed.
See also: How to Change Date and Time Format in Windows 11
Changing file date & timestamp via CMD
The Command Prompt (CMD) is a basic tool in Windows that lets you talk to your computer in a more direct way. You can use CMD for lots of tasks, including messing with file dates and times.
Using the NirCmd command line
Sadly, CMD by itself doesn’t let you change file dates and times directly. But, no worries! You can grab tools like NirCmd or BulkFileChanger to get the job done. Here’s how you can use NirCmd:
- Grab NirCmd from the NirSoft website.
- Unzip it and make sure your computer knows where to find it by updating your system’s PATH.
- Open up CMD as the boss (administrator).
- Go to the folder with the file you want to tweak.
- Use the
nircmd
command withsetfiletime
, add your file’s name, and slap on the dates and times you want. Like this:
nircmd setfiletime "example.txt" "15-03-2023 10:22:30" "15-03-2023 10:22:30" "15-03-2023 10:22:30"
This command updates the creation, last modified, and last accessed dates and times for example.txt
to March 15, 2023, at 10:22:30 AM. Remember to stick to the “dd-mm-yyyy hh:mm:ss” format.
If you run into trouble changing a file because of permissions, check out: How to Take Ownership of a File, Folder or Drive in Windows 11.
NirCmd also has a neat “now” trick. If you use “now” as your date and time, it sets everything to the current moment, which is handy if you don’t want to type out the exact time. Like so:
nircmd setfiletime "example.txt" now now now
Batch change file date & timestamp using the “for /r” loop with NirCmd
The for /r
loop in CMD is a smart way to go through files and folders, even the ones inside other folders. While CMD doesn’t let you change dates and times on its own, combining for /r
with NirCmd can help you update lots of files at once.
Useful tip: How to Batch Rename Files in Windows 11
Basic Syntax of the for /r
Loop
Here’s the basic idea behind using for /r
:
for /r [Path] %i in ([SearchMask]) do [Command] %i
[Path]
: Where to look. If you skip this, it uses the folder you’re in.[SearchMask]
: Helps you pick which files to work on, like*.txt
for text files.[Command] %i
: What you want to do to each file. The%i
is each file it finds.
Modifying file date and timestamp attributes recursively with for /r
Loop and NirCmd
To change dates and times for a bunch of files with for /r
and NirCmd, do this:
- Make sure NirCmd’s folder is in your system’s PATH as mentioned before.
- Open CMD and go to the folder with the files you want to update.
- Run the
for /r
loop with NirCmd to update each file. Here’s an example:
for /r %i in (*) do nircmd setfiletime "%i" "15-03-2023 10:23:38" "15-03-2023 10:23:38"
This will adjust the creation and modification dates and times for all files to March 15, 2023, 10:23:38 AM.
Related issue: Batch (.BAT) Files Not Running in Windows 11/10
How to change file date & timestamp with PowerShell
PowerShell is a step up from the old command-line interface, CMD. It’s got lots of cool tools built right in that let you do all sorts of things, like changing when a file says it was made or last changed (the date and time attributes).
Getting to know the “Set-ItemProperty” cmdlet
The Set-ItemProperty
cmdlet is super handy. It lets you change details about files, including when they say they were made or last updated.
Also see: How to move all files from subfolders to the main folder in Windows
How to use the Set-ItemProperty
cmdlet
Here’s how you use to the Set-ItemProperty
cmdlet:
Set-ItemProperty -Path [Path] -Name [PropertyName] -Value [NewValue]
- For
-Path [Path]
, tell it where the file is. - With
-Name [PropertyName]
, say which detail you’re changing. - And
-Value [NewValue]
, well, that’s the new detail you’re setting.
Changing when a file says it was made or last updated
To change a file’s date and time info with Set-ItemProperty
, do this:
- Pop open a PowerShell window.
- Create a new date and time object with
Get-Date
. Like this:$NewDate = Get-Date -Year 2023 -Month 3 -Day 15 -Hour 10 -Minute 22 -Second 30
This sets up a date and time for March 15, 2023, at 10:22:30 AM.
- Now, use
Set-ItemProperty
to update the file. Like so:Set-ItemProperty -Path "example.txt" -Name CreationTime -Value $NewDate Set-ItemProperty -Path "example.txt" -Name LastWriteTime -Value $NewDate
These steps will set the created and modified dates for example.txt
to March 15, 2023, 10:22:30 AM.
Changing the last accessed date too
You can also update when a file was last opened with the same cmdlet. Just like this:
Set-ItemProperty -Path "example.txt" -Name LastAccessTime -Value $NewDate
Now, example.txt
will show it was last opened on March 15, 2023, 10:22:30 AM.
Additional resource: Figuring out which process is using a file in Windows 11
Batch changing dates & times for multiple files
The ForEach-Object
cmdlet is great for doing the same thing to lots of files at once. You can grab a bunch of files with Get-ChildItem
and then tell ForEach-Object
what to do with each one.
Basic steps for using ForEach-Object
Here’s how you get started:
Get-ChildItem [Path] | ForEach-Object { [ScriptBlock] }
[Path]
is where your files are.- And
[ScriptBlock]
is what you want to do to each file.
Changing dates and times for a bunch of files
Here’s how to update a lot of files all at once:
- Fire up a PowerShell window.
- Make a new date and time object with
Get-Date
, just like before. - Find the files with
Get-ChildItem
, and then letForEach-Object
do its thing. Check it out:Get-ChildItem -Path "C:\example\*.txt" | ForEach-Object { Set-ItemProperty -Path $_.FullName -Name CreationTime -Value $NewDate Set-ItemProperty -Path $_.FullName -Name LastWriteTime -Value $NewDate }
Note: Type these lines one by one, hitting Shift + Enter to go down a line. Hit Enter only when you’ve typed it all in.
This will change the created and modified dates for all .txt
files in C:\example
to March 15, 2023, 10:22:30 AM.
Changing dates and times in folders and their subfolders
If you’ve got files in folders within folders, add the -Recurse
option to Get-ChildItem
. Like this:
Get-ChildItem -Path "C:\example\*.txt" -Recurse | ForEach-Object { Set-ItemProperty -Path $_.FullName -Name CreationTime -Value $NewDate Set-ItemProperty -Path $_.FullName -Name LastWriteTime -Value $NewDate }
Now, all .txt
files in C:\example
and its subfolders will have their dates changed to March 15, 2023, 10:22:30 AM.
Some final words
This guide has shown you how to update when files say they were created or last modified using both CMD and PowerShell. While you need extra tools to do it with CMD, using PowerShell is much easier because the needed commands are already built right into it. Knowing how to change these attributes of files should help you with organizing them, syncing stuff up, or figuring out problems when they pop up.
Сообщение от EvgenyV
Ноги тут не при чем…
Это обычное заблуждение, EvgenyV,
ноги очень нужны, например, чтобы сходить в Гугл и почитать как организован процесс хранения и поиска информации,
используя файловые системы ОС Windows, да и других систем тоже.
Я же совсем вкратце могу тебе рассказать о причинах моего скепсиса.
Дело в том, что ОС берёт на себя манипулирование метаданными файла:
—
Временем создания
,
временем последнего изменения
,
временем последнего доступа
,
размером, признаком архивации, признаком индексации, признаком сжатости, признаком шифрования, признаком скрытости, признаком системности, данными по контролю доступа, типом хранящихся данных.
Кроме того т.н офисные файлы несут в себе доп. информацию о времени, перс.данных пользователя/компании и прочие доп. категории.
ОС может предоставить тебе доступ к этим метаданным, а также предоставить возможность их изменения.
Таким образом нет никакой нужды самостоятельно дублировать временные атрибуты, запихивая их в имя файла.
Если такая нужда есть, это скорее всего означает, что у ты выбрал неудачный файловый менеджер либо не умеешь пользоваться его возможностями.
Предлагаю свой вариант маленькой примочки, которая добавляет в имя файла дату его создания.
Для чего я ее сделал? В процессе разработки чего-либо я делаю резервную копию, отправляя в архив папку с проектом целиком: щелкаем правой кнопкой мыши по папке или файлу проекта и выбираем в контекстном меню «Отправить» в «Сжатая zip папка». Получаем архивированную копию и переносим ее в папку с архивами. Хорошо, но завтра, повторяя те же действия, я получу архивный файл с таким же именем, как и сегодня. Да, при переносе в папку с архивом, новый файл заменит старый. Но иногда требуется отследить изменения, происходившее в проекте (ну не все же среды разработки имеют функцию Истории). А, может, на каком-то этапе эволюция проекта завела нас не в ту сторону и надо откатиться? В таком случае нам надо накапливать свои резервные копии. Я это делаю, добавляя в имя резервного файла дату его создания. Автоматизируем процесс, встроив такую функцию в контекстное меню файлового менеджера.
Создадим в текстовом редакторе файл с именем retime.bat со следующим содержанием и разместим его, например, в корне диска С:
echo off
set file=%1
If Exist %file% For %%i In (%file%) Do SET psth=%%~pi
If Exist %file% For %%i In (%file%) Do SET TIMESTAMP=%%~ti
If Exist %file% For %%i In (%file%) Do SET nn=%%~ni
If Exist %file% For %%i In (%file%) Do SET xx=%%~xi
setlocal enabledelayedexpansion
for /f «tokens=1 delims=’.’» %%i in (‘echo %TIMESTAMP%’) do set dd=%%i
for /f «tokens=2 delims=’.’» %%i in (‘echo %TIMESTAMP%’) do set mm=%%i
for /f «tokens=3 delims=’.’» %%i in (‘echo %TIMESTAMP%’) do set yy=%%i
for /f «tokens=1» %%i in (‘echo %yy%’) do set yy=%%i
rename %file% «%nn%_%yy%%mm%%dd%%xx%»
В двух словах: разбираем информацию о файле на имя (nn), расширение (xx) и время его создания (TIMESTAMP); парсим время создания, выделяя год (yy), месяц (mm) и день (dd) и собираем новое название. Например, у нас был project1.zip, созданный 14 марта 2014 года, после переименования получаем project1_20140314.zip. Дата сделана «с заду наперед» для правильной сортировки по имени файла – файлы выстроятся в соответствии с датой создания. Хотите по-другому – измените строку, начинающуюся с rename.
Теперь сделаем запуск нашего bat файла из контекстного меню. Для этого опять же в текстовом редакторе создаем файл reg_retime.reg с таким содержимым:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\Retime\Command]
@=»\«C:\\retime.bat\» \»%1\»»
Обратите внимание – Retime – так будет выглядеть команда в контекстном меню. Так же мы указываем путь к нашему bat файлу. Щелкаем по созданному файлу и соглашаемся добавить данные в реестр. Готово!
Проверяем: берем файл — подопытного кролика, щелкаем по нему правой кнопкой мыши и выбираем в открывшемся контекстном меню пункт Retime. К имени подопытного кролика добавится дата его создания.