Make Temporary Files Easier to Create
The FileSystemObject object's GetTempName method gives you a random filename for a file in which you plan to store temporary data. To create a randomly generated temporary filename and place the name in a variable, you need only the two lines of code that Listing 3 shows. However, the GetTempName method has some drawbacks in a production environment.
First, the filename isn't a complete path. If you try to use the temporary filename directly, your temporary files will end up in the script's current folder rather than Windows' standard Temp folder.
Second, the names that GetTempName provides aren't unique. Because the names are random, a file with the same name might already exist. You probably won't have trouble if you use only a few temporary files, but if you use many temporary files, you might have problems.
Finally, GetTempName gives you a name but doesn't do any work for you. You must manually open the temporary file, then write the data to the file.
To make temporary files easier to create, I wrote the NewTemporaryFile function, which Listing 4, page 16, shows. Like GetTempName, NewTemporaryFile generates a random filename, but the function builds the filename into a complete path in the current user's Temp folder. Using a full path ensures that you don't accidentally scatter data into multiple files if your script changes directories while running. In addition, if your script crashes while running or if you forget to explicitly delete the temporary files when the script ends, you can find all the files in the user's Temp folder. This procedure helps secure potentially sensitive data in the temporary file and increases the likelihood that the file will be automatically removed during regular system maintenance.
NewTemporaryFile uses GetTempName to generate the random filename. However, unlike GetTempName, NewTemporaryFile checks to see whether the filename is unique. If the filename isn't unique, NewTemporaryFile prompts GetTempName to generate a new random filename. This process continues until the filename is unique. At that point, the function writes the specified data to the file and returns the filename.
To use NewTemporaryFile in your scripts, place the function at the end of your code. Then, at the appropriate spot in the script, you need to call the function, following the syntax
where File Text is the text you want to write to the temporary file. So, for example, if you want to write Scripts rule to the temporary file and display its filename on screen, you'd add the following code to your script:
The f variable will contain the full path to your temporary file.