Why GetTempFileName() is Evil

by Oct 14, 2015

Some may have come across a .NET call that is supposed to generate random temporary file names:

$path = [System.IO.Path]::GetTempFileName()
$path  

And it does. But it does more. It actually creates an empty file with that file name:

 
PS C:\> Test-Path $path 
True 
 

If you don't clean up your temp files, you will even get an exception once 65535 temporary files have been created.

In PowerShell 5.0, New-TemporaryFile does the exact same thing, except here the file is returned so you immediately recognize that you actually created a file, not a filename.

Twitter This Tip! ReTweet this Tip!