Thursday, November 12, 2015

New functionality for working with temp files in PowerShell 5

Sometimes you need to store data in a script. If you decided to stick it in a temp file, in the past you had to figure out where to create the file, confirm the location exists at runtime, figure how to name the file, and handle possible name conflicts. Or maybe you just decided not to use a temp file just so you could avoid those complications.

In PowerShell 5, we have a new command that handles all of the automatically.

New-TemporaryFile

New-TemporaryFile takes no parameters (other than “common” parameters), so it’s very simple to use.

It gets the location of the temp folder for the current user. If the script is running in the context of a user, this will be a user-specific folder. The exact location will vary from one OS version to another.
If the script is running under the local SYSTEM or NETWORK account, this will be the machine temp folder.

It creates an empty file with a name like tmpD435.tmp. The four random hex characters are guaranteed to be unique in the folder. You can create over 65,000 of them in your temp folder before running out of names.

It returns a fileinfo object giving you the details on the file it created.

So let’s say we want to have a script that dumps details to a temp file, and then either deletes the file if the script is successful, or opens it for the person running the script to see the details. It would look something like this.

001
002
003
004
005
006
007
008
009
010
011
012
013
$LogFile = New-TemporaryFile
## Code
"Log entry" | Out-File -FilePath $LogFile.FullName -Append
## More code
"Another log entry" | Out-File -FilePath $LogFile.FullName -Append
If ( $Success )
    {
    $LogFile | Remove-Item
    }
Else
    {
    Start $LogFile
    }

1 comment:

  1. This was previously available as a .Net method, but PS ver5 makes it much more friendly with the native cmdlet.

    [System.IO.Path]::GetTempFileName()

    ReplyDelete