Developing a naming strategy for temporary files or output files lets you ensure that an instance of a script doesn't unintentionally overwrite another file. One naming approach is for the script operator to specify the filename in the script header. I usually try to avoid this option and instead include code in the script that automatically generates the filenames if for no other reason than to avoid the possibility of typos.

I typically use one of three methods to create unique filenames. The first method is file-path substitution. If your script takes input that includes file paths, you can use the file-path information to create a path-based filename after you strip out the slash (\) and colon (:) characters by using string substitution. Remember, you can't use these characters in a filename. This method is ideal for dealing with output files because it lets you easily identify what path location the report (i.e., output file) relates to. You can use a similar technique to deal with spaces and any other characters that you want to strip or replace in a path. The following sample code changes a path into a filename:

Set Path=\\servera\share37\wilma
Set Path=%Path::\=-%
Set Path=%Path:\=-%
Set Pathfn=%Path%.txt
Echo %Pathfn%

The second method is to convert the date and time to a filename. This method is best if you want to name reports for the time of day that the script runs. To create a date-based filename, use this syntax:

For /F "tokens=2,3,4,5,6,7,8
  delims=/ " %%i in ("%DATE%")
  Do Set Dfn=D%%i-%%j-%%k.txt
Echo %Dfn%

To generate a combination date-and time-based filename, use this syntax:

For /F "tokens=2,3,4,5,6,7,8
  delims=/: " %%i in ("%DATE% %TIME%")
  Do Set DTfn=
  D%%i-%%j-%%k-T%%l-%%m-%%n.txt
Echo %DTfn%

The third method works well for temporary files in cases where intuitive filenames aren't important, because only the script will be creating, using, and deleting the files. I used this method in the ReplicationTest script. Generally, the only time you'd need to access such temporary files is for script-debugging purposes, so friendly filenames aren't really necessary.

The code below uses the RANDOM environment variable to create a random filename for the temporary files that ReplicationTest uses:

Set Ranfn=%RANDOM%.txt
Echo %Ranfn%