CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – How to create temporary files?

Yet times, we need to create temporary files in PowerShell scripts to store the temporary data for the program’s needs. These files are created in the temporary folder which was set in the Operating System configuration.

PowerShell provides New-TemporaryFile cmdlet to do the job for us to create a temporary file(s) through the scripts.

Create temporary files in PowerShell

New-TemporaryFile cmdlet is used to create the temporary file(s) in the temporary directory. Usually, it creates the file name as “tmpXXXX.tmp”, where ‘XXXX’ is the random hexadecimal number to avoid any conflicts with the existing file names. Here is an example;

PS C:\> New-TemporaryFile

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

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        11-19-2021     18:33              0 tmp5EA3.tmp

Did you expect this command simply returns the temporary file name? You might have known already that PowerShell commands return the objects; this command returns the FileInfo object; hence you are seeing the above details of the temporary file. Using the GetType() method, we can retrieve the type of an object. Here is an example;

PS C:\> (New-TemporaryFile).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     FileInfo                                 System.IO.FileSystemInfo

Then, how do we get the temporary filename? Well, FileInfo object has FullName property and by accessing this, we can get the full name of the temporary file. We need to store this into a variable to use the same file name; otherwise, every time we call this command it will create a new temporary file.

PS C:\> $TempFile = (New-TemporaryFile).FullName
PS C:\> $TempFile
C:\Users\david\AppData\Local\Temp\tmp9E59.tmp

Observe that, the command should be enclosed in parentheses (“()”), otherwise we will get the below error.

PS C:\> New-TemporaryFile.FullName
New-TemporaryFile.FullName : The term 'New-TemporaryFile.FullName' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again.
At line:1 char:1
+ New-TemporaryFile.FullName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (New-TemporaryFile.FullName:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

[David]

PowerShell – How to create temporary files?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top
Exit mobile version