#powershell Temporary Files

Introduced in PowerShell 5.0, the New-TemporaryFile cmdlet creates a single ‘scratch’ file with the tmp file extension in a user’s $env:temp directory. For previous #powershell versions, you can do this directly with .NET Framework:

$tempfile = [system.io.path]::GetTempFileName()

Likewise, this has the tmp file extension and is automatically placed in $env:temp. Assigning to a variable permits quick access.

Alternatively, you can create a unique file name for temporary usage by taking advantage of your system date/time as depicted:

$d = Get-Date
$d1 = $d.date.ToShortDateString() -replace “:|/|-|\.”
$d2 = $d.TimeOfDay.ToString() -replace “:|\|-|\.”
$tempfile = “$env:temp\” + $d1 + $d2 + “.tmp”
$tempfile

Leave a Reply