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
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)
}
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)
}
How likely is it that GetRandomFileName
will return a name that already exists in the temp folder?
XXXXXXXX.XXX
where X can be either a lowercase letter or digit.GetRandomFileName
NewGuid
on the other hand can be one of 2^122 possibilities, making collisions all but impossible.
.NET has had [System.IO.Path]::GetTempFileName()
for quite a while; you can use this to generate a file (and the capture the name), then create a folder with the same name after deleting the file.
$tempfile = [System.IO.Path]::GetTempFileName();
remove-item $tempfile;
new-item -type directory -path $tempfile;