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 } |
This was previously available as a .Net method, but PS ver5 makes it much more friendly with the native cmdlet.
ReplyDelete[System.IO.Path]::GetTempFileName()