Create Unique File Name in Windows Batch: How-To
In this article
To create a unique file name in a Windows batch file, use the current date and time with %DATE% and %TIME%, strip out the characters Windows does not allow in file names (colons, slashes, spaces), and append a random number or process ID as a fallback. A simple working line is set "name=file_%DATE:~-4%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.txt" followed by set "name=%name: =0%" to replace the leading space that appears before 10 AM. That gives you a name like file_20250115_093045.txt that will not collide with another run in the same second. The rest of this guide explains why each piece is needed, how to make it robust across regional date formats, and how to add a guaranteed-unique suffix when two processes might start at the same moment.
What You'll Need
- Windows 10 or Windows 11 (the commands below work on Windows 7 and 8.1 as well, but the examples target current versions).
- Notepad or any plain-text editor to write the .bat file.
- Permission to save and run the batch file in the folder where you want the output — a normal user folder such as Documents is fine; writing to
C:\WindowsorProgram Fileswill fail without elevation. - No extra tools, downloads, or admin rights for the basic method. The optional random-number trick uses
%RANDOM%, which is built into cmd.exe.
Step-by-Step
- Open Notepad and start with
@echo off. This stops the batch file from printing every command it runs, which keeps the output readable. Save the file with a.batextension, for exampleunique-name.bat, and choose “All Files” in the Save as type box so Notepad does not add.txt. - Turn off delayed expansion problems by using
setlocal. Addsetlocal EnableExtensionson the next line. This keeps any variables you create inside the script from leaking into the parent command prompt and makes%RANDOM%behave predictably. - Build a date stamp from
%DATE%. The format of%DATE%depends on the regional settings of the PC, so do not assume it is alwaysMM/DD/YYYY. The safest approach is to callwmic os get localdatetimeand slice the result, because that output is alwaysYYYYMMDDHHMMSSregardless of region. A working pattern is:for /f "tokens=2 delims==." %%a in ('wmic os get localdatetime /value') do set "dt=%%a"
Thenset "stamp=%dt:~0,8%_%dt:~8,6%"gives you20250115_093045. Note thatwmicis deprecated on newer Windows builds; if it is missing, fall back to the%DATE%and%TIME%method in the next step. - Fall back to
%DATE%and%TIME%ifwmicis unavailable. Use substring extraction to pull the pieces you need. For a typical US formatMM/DD/YYYY,%DATE:~-4%is the year,%DATE:~4,2%is the month, and%DATE:~7,2%is the day. For time,%TIME:~0,2%is the hour,%TIME:~3,2%the minute, and%TIME:~6,2%the second. Concatenate them with underscores. Test the output by runningecho %DATE% %TIME%in a command prompt first so you know which positions to slice. - Remove characters Windows forbids in file names. A file name cannot contain
\ / : * ? " < > |. The time string contains colons, so replace them. The cleanest way isset "stamp=%stamp::=-%"which turns09:30:45into09-30-45. Also replace any spaces with zeros:set "stamp=%stamp: =0%". Without this, a run at 9:05 AM produces a name beginning with a space, and Windows will accept it but many tools and scripts will not. - Add a random or process-based suffix for true uniqueness. Two batch files started in the same second will produce the same timestamp. Append
%RANDOM%, which returns a number from 0 to 32767, or use%PROCESSID%if you have captured it (the variable is not set by default; you can get it withwmic process where processid=%cmdcmdline%but that is fragile). The simplest reliable option isset "name=output_%stamp%_%RANDOM%.txt". The chance of a collision is small enough for most scripts, and you can loop if you need a guarantee. - Check that the file does not already exist and loop if it does. Wrap the name generation in a label and use
if exist "%name%" goto :retry. On the retry, regenerate the random suffix. This turns a probabilistic fix into a guaranteed one, at the cost of a few lines. A short example::retryset "name=output_%stamp%_%RANDOM%.txt"if exist "%name%" goto :retry - Use the variable in your command. Once
%name%holds a safe, unique string, pass it to whatever writes the file, for exampleecho hello > "%name%"orcopy source.txt "%name%". Always wrap the variable in double quotes so spaces or unusual characters do not break the command. - Test with a dry run. Before wiring the script into a scheduled task, run it manually from a command prompt with
echo %name%added temporarily. Confirm the output looks like a valid file name and that no colon, slash, or leading space survived. Then remove theecholine and run it for real.
Common Mistakes
- Assuming
%DATE%is alwaysMM/DD/YYYY. On a UK or German machine it may beDD/MM/YYYYorDD.MM.YYYY, so the same substring positions give a different result. Always test on the target machine, or usewmic os get localdatetimewhich is region-independent. - Forgetting the leading space before 10 AM.
%TIME%returns9:05:45with a leading space, not09:05:45. Replacing spaces with zeros fixes it; skipping this step produces file names that start with a space and are hard to open from Explorer. - Leaving colons in the name. Windows will reject the file with “The filename, directory name, or volume label syntax is incorrect.” Replace colons before using the variable.
- Using
%RANDOM%without a loop. Two scripts launched by the same scheduled task at the same second can still collide. Theif existretry loop is the fix. - Not quoting the variable.
echo hello > %name%breaks if the name contains a space. Use> "%name%".
Tips
- Keep the timestamp in a sortable order: year first, then month, day, hour, minute, second. That way a folder listing sorts chronologically without extra work.
- Use a short prefix such as
log_orbackup_so files are easy to find with wildcards likelog_*.txt. - If you need a unique name but not a timestamp,
%RANDOM%%RANDOM%gives a wider range than a single call, and combining it with the process ID makes collisions very unlikely. - Test the script on the same regional settings as the machine that will run it. A script that works on your PC may produce a malformed name on a colleague's PC with different date settings.
- Store the generated name in a variable once and reuse it; regenerating it mid-script will produce a different name and you will write to two files.
Troubleshooting
If the script runs but the file name looks wrong, add echo %name% and pause before the write step so you can see exactly what is being generated. If the name contains a colon or a leading space, the replacement lines are missing or in the wrong order. If the file is created but empty, check that the redirection uses > and not >> unless you intend to append. If you get “Access is denied,” the script is running in a protected folder; move it to Documents or run it as administrator. If wmic is not recognised, the command has been removed from your Windows build; fall back to the %DATE% and %TIME% method. If two runs still collide, the retry loop is missing or the goto :retry label is misspelled.
Frequently Asked Questions
Can I use %DATE% and %TIME% directly in a file name?
No. %TIME% contains colons, which Windows does not allow in file names. You must replace them, for example with hyphens, before using the string.
Why does my file name start with a space?
%TIME% pads single-digit hours with a space, not a zero. Replace spaces with zeros using set "stamp=%stamp: =0%" after building the string.
Is %RANDOM% guaranteed to be unique?
No. It returns a number between 0 and 32767, so collisions are possible. Combine it with a timestamp and an if exist retry loop if you need a guarantee.
Does this work on Windows 11?
Yes. The batch commands are the same. Note that wmic is deprecated on recent builds, so prefer the %DATE% and %TIME% method or PowerShell if wmic is missing.
Can I generate a unique name in PowerShell instead?
Yes. PowerShell has Get-Date -Format 'yyyyMMdd_HHmmss' and [guid]::NewGuid(), both of which avoid the regional-format and colon problems entirely. Use batch only if the rest of your script is already batch.
What characters are not allowed in Windows file names?
The characters \ / : * ? " < > | are forbidden, along with names ending in a space or a period. Stick to letters, digits, underscores, and hyphens for portable names.