functions/filesystem/New-TemporaryDirectory.ps1
function New-TemporaryDirectory { <# .SYNOPSIS Creates a new temporary directory with a unique name. .DESCRIPTION Generates a uniquely named temporary directory in the system's TEMP folder using a new GUID. Optionally appends a subfolder name. Returns the created directory as a DirectoryInfo object. If the directory already exists (which is extremely unlikely due to GUID usage), it returns the existing directory. .PARAMETER Name An optional name to append as a subdirectory inside the generated temp folder. .OUTPUTS System.IO.DirectoryInfo .EXAMPLE New-TemporaryDirectory Creates a temporary directory with a unique name in the system TEMP folder. .EXAMPLE New-TemporaryDirectory -Name 'Logs' Creates a temporary directory with a unique GUID and appends a 'Logs' subdirectory to it. .NOTES Author: Jascha Vincke #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [string]$Name ) $tempRoot = Join-Path -Path $env:TEMP -ChildPath $([guid]::NewGuid().Guid) if (-not [string]::IsNullOrWhiteSpace($Name)) { $tempRoot = Join-Path -Path $tempRoot -ChildPath $Name } if (-not (Test-Path -Path $tempRoot)) { Write-Verbose "Creating temp directory: $tempRoot" return New-Item -Path $tempRoot -ItemType Directory -Force } else { Write-Verbose "Temp directory already exists: $tempRoot" return Get-Item -Path $tempRoot } } Set-Alias -Name New-TempDirectory -Value New-TemporaryDirectory -Description 'Prevent breaking scripts using New-TempDirectory after function has been renamed (2025-06-08).' |