Public/Common/New-TempDirectory.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
function New-TempDirectory { [CmdletBinding()] param () begin {} process { # It's EXTREMELY unlikely but just to be safe we'll make sure we get a directory name that doesn't already exist $Count = 0 try { $TempDirName = ( -join ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count 8 | ForEach-Object { [char]$_ })) $TempDirPath = Join-Path (Get-PSDrive Temp).Root $TempDirName while ((Test-Path $TempDirPath) -and $Count -lt 10) { Write-Verbose "Temp directory $TempDirPath already exists, choosing another name." $Count = $Count + 1 $TempDirName = ( -join ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count 8 | ForEach-Object { [char]$_ })) $TempDirPath = Join-Path (Get-PSDrive Temp).Root $TempDirName } if ($Count -ge 10) { throw "Unique name attempts exceeded." } $TempDirectory = New-Item $TempDirPath -ItemType Directory -Force } catch { throw "Failed to create temp directory.`n$($_.Exception.Message)" } } end { if ($TempDirectory) { Return $TempDirectory } } } |