Create a temporary directory in PowerShell?

Michael Kropat picture Michael Kropat · Jan 1, 2016 · Viewed 36.3k times · Source

PowerShell 5 introduces the New-TemporaryFile cmdlet, which is handy. How can I do the same thing but instead of a file create a directory? Is there a New-TemporaryDirectory cmdlet?

Answer

Michael Kropat picture Michael Kropat · Jan 1, 2016

I think it can be done without looping by using a GUID for the directory name:

function New-TemporaryDirectory {
    $parent = [System.IO.Path]::GetTempPath()
    [string] $name = [System.Guid]::NewGuid()
    New-Item -ItemType Directory -Path (Join-Path $parent $name)
}

Original Attempt With GetRandomFileName

Here's my port of this C# solution:

function New-TemporaryDirectory {
    $parent = [System.IO.Path]::GetTempPath()
    $name = [System.IO.Path]::GetRandomFileName()
    New-Item -ItemType Directory -Path (Join-Path $parent $name)
}

Analysis Of Possibility Of Collision

How likely is it that GetRandomFileName will return a name that already exists in the temp folder?

  • Filenames are returned in the form XXXXXXXX.XXX where X can be either a lowercase letter or digit.
  • That gives us 36^11 combinations, which in bits is around 2^56
  • Invoking the birthday paradox, we'd expect a collision once we got to around 2^28 items in the folder, which is about 360 million
  • NTFS supports about 2^32 items in a folder, so it is possible to get a collision using GetRandomFileName

NewGuid on the other hand can be one of 2^122 possibilities, making collisions all but impossible.