If you've been a Perl programmer, you've probably used
File::Temp occasionally, to generate unique filenames for temporary files and clean up afterwards. In other lanuages you may have used a variation of the standard
POSIX tmpnam or tmpfile.
In PowerShell, you'll often need to generate temporary files, especially if you're working with import-csv or import-clixml -- as they don't support data on the pipeline.
There's not (yet) anything I could find that is quite as nice as File::Temp, but if you want to generate a unique filename or directory name, or create a temp file on disk ready to be used, you can use these methods on System.IO.Path:
System.IO.Path.GetRandomFileName() [msdn]Returns a random folder name or file name. The filename generated is cryptographically secure, meaning that no malicious script should be able to guess what filename you've just been given.
To use from PowerShell:
53> $filename = [System.IO.Path]::GetRandomFileName()
54> $filename
lbhrurye.uhp
55> Get-ChildItem > $filenameSystem.IO.Path.GetTempFileName() [msdn]This method will actually create a temporary file on disk, in your temp directory (returned by System.IO.Path.GetTempPath). The file is 0 bytes, and ready for you to clobber with your own content. You can be sure that no other process has generated the same filename, but it's not exactly a secret what filename you've got -- you should use the GetRandomFileName method if you need a bit of security.
To use from PowerShell:
59> $filename = [System.IO.Path]::GetTempFileName()
60> get-childitem | export-csv $filename
The other thing to remember with GetTempFileName is that you need to remember to delete the temp file after you're finished (something that File::Temp does quite nicely for Perl'ers). Some day I might write a wrapper that deletes the file when the variable goes out of scope.