Problem
You want to create a file for temporary purposes and want to be sure that the file does not already exist.
Solution
Use the [System.IO.Path]::GetTempFilename() method from the .NET Framework to create a temporary file:
$filename = [System.IO.Path]::GetTempFileName() (... use the file ...) RemoveItem Force $filename
Discussion
It is common to want to create a file for temporary purposes.
Often, people create this temporary file wherever they can think of: in C:\, the script’s current location, or any number of other places. Although this may work on the author’s system, it rarely works well elsewhere. For example, if the user does not use their Administrator account for daytoday tasks, your script will not have access to C:\ and will fail.
Another difficulty comes from trying to create a unique name for the temporary file. If your script just hardcodes a name (no matter how many random characters it has), it will fail if you run two copies at the same time. You might even craft a script smart enough to search for a filename that does not exist, create it, and then use it. Unfortunately, this could still break if another copy of your script creates that file after you see that it is missing—but before you actually create the file.
Finally, there are several security vulnerabilities that your script might introduce should it write its temporary files to a location that other users can read or write.
Luckily, the authors of the .NET Framework provided the [System.IO.Path]:: GetTempFilename() method to resolve these problems for you. It creates a unique filename in a reliable location in a secure manner. The method returns a filename, which you can then use as you want.
Remember to delete this file when your script no longer needs it; otherwise, your script will waste disk space and cause needless clutter on your users’ systems. Remember: your scripts should solve the adminis
trator’s problems, not cause them!
By default, the GetTempFilename() method returns a file with a .tmp extension. For most purposes, the file extension does not matter, and this works well. In the rare instances when you need to create a file with a specific extension, the [System.IO. Path]::ChangeExtension() method lets you change the extension of that temporary file. The following example creates a new temporary file that uses the .cs file extension:
$filename = [System.IO.Path]::GetTempFileName() $newname = [System.IO.Path]::ChangeExtension($filename, ".cs") MoveItem $filename $newname (... use the file ...) RemoveItem $newname