Script for creating a temp file

Sep 13, 2007 at 2:12 PM
I needed to easily create a temp file and noticed there are no commands built in for that. True, there is the IO.Path.GetTempFileName, but it doesn't really do things the Powershell way. So intead, I wrote my own script to create files called New-TempFile.ps1. It currently doesn't have error checking, but it might be useful to some people. It returns a FileInfo object, so it is fairly easy to work with the results.

Here's a small example used to send an attachment in an email.

$tf = .\New-TempFile.ps1 "csv"
dir | select name, length | Export-Csv -NoTypeInformation $tf
Send-SmtpMail -To "" -Subject "dir output" -AttachmentPath $tf
Remove-Item $tf
$tf =$null

# New-TempFile.ps1
# Creates a Temp File in the temp directory and optionally uses the extension specified.
# Returns: System.IO.FileInfo
# Note: Delete the tempfile when you're done with it.
param ( [string]$Extension )
$RandomFileName = [System.IO.Path]::GetRandomFileName()
if ($Extension -ne "") { $RandomFileName = [System.IO.Path]::ChangeExtension($RandomFileName, $Extension) }
New-Item -Path $($Env:TEMP) -Name $RandomFileName -ItemType File

Of course, if something like this already exists and I didn't find it, then please let me know about it.

Sep 15, 2007 at 8:17 PM
I really like the idea of having a New-TempFile command. Just not sure about the implementation GetTempFileName has the nice property of creating the file for you before it returns eliminating any possible race condition of file creation. Perhaps we could have two commands here: New-TempFile and New-RandomFileName?? Just a thought. I'd like to get a little more feedback on this and then I'll convert this to a work item for the 1.2 release.
Sep 17, 2007 at 5:44 AM
I also like that the GetTempFileName creates the file for you, but there are a few limitations. First, if someone isn't deleting their temp files or they need a lot of temp files, they will get an error if they end up generating more than about 65000 files. Second, sometimes you want it to have a specific extension ( csv, txt, log, ...) and if you use the GetTempFileName, you would then still need to rename the file and possible run into issues. Third, GetTempFileName returns a string path to the file. If you want to do anything else with it that depends on the FileInfo properties, then you would still need to get the item so you would be able to use the properties.

I also thought about the idea of a New-RandomFileName script (actually Get-RandomFileName since it didn’t create the file). I decided that the only time I wanted a random filename, is when I wanted a temp file and not a name to be used elsewhere. That’s why I stuck with New-TempFile. I guest I could see the usefulness for others, but I'm not sure when I would use it.