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-TemporaryDirec
If you want the looping solution that is guaranteed to be both race- and collision-free, then here it is:
function New-TemporaryDirectory {
$parent = [System.IO.Path]::GetTempPath()
do {
$name = [System.IO.Path]::GetRandomFileName()
$item = New-Item -Path $parent -Name $name -ItemType "directory" -ErrorAction SilentlyContinue
} while (-not $item)
return $Item.FullName
}
According to the analysis in Michael Kropat's answer, the vast majority of the time, this will pass only once through the loop. Rarely will it pass twice. Virtually never will it pass three times.