The successor to New-TemporaryFile is, you might have guessed it, New-TemporaryDirectory 🙂 In this small blog post, I will show you how it works and a few use cases.
Why should I care?
Well… The location of the temp folder depends on which user you are running a script as, what platform you are on, etc. I sometimes write some logic to create a random folder to avoid reusing an existing location, and the New-TemporaryDirectory cmdlet was first introduced in the preview versions of PowerShell v7.7 to make things easier.
You can check the issue logged in 2025 requesting that function, which follows the New-TemporaryFile approach, here: https://github.com/PowerShell/PowerShell/issues/25754. Mentioned in the PR is also:
“The working group recommended adding New-TemporaryDirectory so users can create temporary directories without calling [System.IO] directly. That matters in constrained and restricted language modes where direct .NET type access is not available.” (Source: https://github.com/PowerShell/PowerShell/pull/27549, and thanks Kirtikumar Anandrao Ramchandani for this!)
And that’s the other use case; this also works around having restrictions in your environment 🙂
How does it work?
When running PowerShell v7.7 (Or later), the New-TemporaryDirectory Cmdlet is available. Running it without any parameters will result in a random Directory name:

I used the -Verbose Parameter to show the directory location while creating it. The Cmdlet has only one Parameter, in addition to the default ones, to specify a Prefix for the Directory name. For example:

I used the -Verbose Parameter to show its location while creating a directory with the Prefix PSIF. (I’m on a Mac system; on Windows, it will be somewhere in c:\Windows\Temp or c:\Users\username\AppData\Local\Temp, for example) To reuse its name, you can store it in a Variable while creating it:
<div class="cm-line">$TempFolder=New-TemporaryDirectory -Prefix PSIF</div>
When you look at $TempFolder, you will see this for $TempFolder.FullName:
<div class="cm-line">$TempFolder.FullName</div><div class="cm-line">/var/folders/kd/tdp12tsd6670ztkbt0pf48zh0000gn/T/PSIFK30uOn</div>
Now you can use the Variable $TempFolder to create new items in a randomly named folder, which you can clean up after running your code:
<div class="cm-line">Remove-Item -Path $TempFolder.FullName -Recurse -Force:$true -Confirm:$false</div>
Wrapping up
And that’s how you use the newly available New-TemporaryDirectory Cmdlet. Have a lovely weekend!
