Tuesday, April 14, 2009

Create unique temp filename with Batch script

For Windows batch scripts, you could use %RANDOM% to generate a random number and use that as part of the temp file name but that doesn't guarantee uniqueness since random number can be repeated. By adding another variable to the mix, seconds and fraction of seconds, the file name would be unique:

echo "Temp file name is %TMPFILE%"
goto :EOF

set TMPFILE=%TMP%\mytempfile-%RANDOM%-%TIME:~6,5%.tmp



Flat File Cabinets Used said...

I'm so
love this blog, already bookmarked it! Thanks.

Ildar Shaimordanov said...

This is not universal solution. It does not guarantee unique values in
pipes. Consider a situation when two scripts (this can be one script or
two different scripts) communicate via pipe. If both of them use the
same algorithm to create a unique value then sometimes they can face a
collision trying to process single file.

The illustration  is here. Store your example as teh script.bat file and run it several times:
script>&2 | script>&2

AndresVia said...

 This is enough uniqueness for me...

Guest said...

%TIME% can have different formats so it will maybe not work on other systems