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.
Можно немного автоматизировать, добавив (или изменив имеющийся) диалог в контекстное меню папок (можно даже для конкретной папки):
Добавляет новый пункт в контекстное меню папок.
HKLM\SOFTWARE\Classes\Directory\shellВ этом разделе необходимо создать новый ключ, например:
HKLM\SOFTWARE\Classes\Directory\shell\Far ManagerВ значении по умолчанию укажите название программы, например «Far manager», далее необходимо создать подключ с названием «command», например:
HKLM\SOFTWARE\Classes\Directory\shell\Far Manager\commandВ значении по умолчанию укажите путь к файлу с параметрами при необходимости, например:
c:\program files\far\far.exe %1
Либо создать свою папку для всего этого дела и создавать нужные папки только внутри неё, а для корневой настроить сортировку по дате, добавить (или перенастроить) столбцы как удобно.
Можно создать новый диалог создания файла, достаточно записать имя файла в виде:
имя_файла_%date%.txt
Собственно дата в свойствах файла для того и нужна, мало того — их там две — создания и изменения (есть ещё последнего доступа и кажется, ещё какие-то). Потому что имя файла это имя, а не дата.
Сообщение от EvgenyV
Ноги тут не при чем…
Это обычное заблуждение, EvgenyV,
ноги очень нужны, например, чтобы сходить в Гугл и почитать как организован процесс хранения и поиска информации,
используя файловые системы ОС Windows, да и других систем тоже.
Я же совсем вкратце могу тебе рассказать о причинах моего скепсиса.
Дело в том, что ОС берёт на себя манипулирование метаданными файла:
—
Временем создания
,
временем последнего изменения
,
временем последнего доступа
,
размером, признаком архивации, признаком индексации, признаком сжатости, признаком шифрования, признаком скрытости, признаком системности, данными по контролю доступа, типом хранящихся данных.
Кроме того т.н офисные файлы несут в себе доп. информацию о времени, перс.данных пользователя/компании и прочие доп. категории.
ОС может предоставить тебе доступ к этим метаданным, а также предоставить возможность их изменения.
Таким образом нет никакой нужды самостоятельно дублировать временные атрибуты, запихивая их в имя файла.
Если такая нужда есть, это скорее всего означает, что у ты выбрал неудачный файловый менеджер либо не умеешь пользоваться его возможностями.
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.