Strange Cmdlet: New-TemporaryFile

by Feb 21, 2022

Here’s a cmdlet that sneaked into PowerShell (and Windows PowerShell) and remained almost unnoticed: New-TemporaryFile. It’s amazing to see such a relatively useless cmdlet being part of PowerShell. When you look at its source code, it essentially just calls a simple method:

 
# load module that defines the function:
PS C:\> New-TemporaryFile -WhatIf
What if: Performing the operation "New-TemporaryFile" on target "C:\Users\tobia\AppData\Local\Temp".

# dump function source code:
PS C:\> ${function:New-TemporaryFile}

    [CmdletBinding(
        HelpURI='https://go.microsoft.com/fwlink/?LinkId=526726',
        SupportsShouldProcess=$true)]
    [OutputType([System.IO.FileInfo])]
    Param()

    Begin
    {
        try
        {
            if($PSCmdlet.ShouldProcess($env:TEMP))
            {
                $tempFilePath = [System.IO.Path]::GetTempFileName()            
            }
        }
        catch
        {
            $errorRecord = [System.Management.Automation.ErrorRecord]::new($_.Exception,"NewTemporaryFileWriteError", "WriteError", $env:TEMP)
            Write-Error -ErrorRecord $errorRecord
            return
        } 

        if($tempFilePath)
        {
            Get-Item $tempFilePath
        }
    }
 

At its heart, it calls this:

 
PS> [System.IO.Path]::GetTempFileName()            
C:\Users\tobia\AppData\Local\Temp\tmp671.tmp 
 

The method GetTempFileName() is misleading though because it actually creates a new temporary file each time you call it. New-TemporaryFile points this out in a better way by returning the temporary file object instead of a string path, which essentially is this:

 
PS C:\> Get-Item ([System.IO.Path]::GetTempFileName())


    Directory: C:\Users\tobia\AppData\Local\Temp


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        26.01.2022     12:48              0 tmpC6DF.tmp
 


Twitter This Tip! ReTweet this Tip!