Skip to content

Instantly share code, notes, and snippets.

@YoraiLevi
Created June 15, 2024 00:46
Show Gist options
  • Save YoraiLevi/ee4394992d820c05b9f820a166eaf987 to your computer and use it in GitHub Desktop.
Save YoraiLevi/ee4394992d820c05b9f820a166eaf987 to your computer and use it in GitHub Desktop.
Get temporary directories not just files
function Get-TemporaryDirectory {
<#
.SYNOPSIS
Creates a new temporary directory with a random name.
.DESCRIPTION
The Get-TemporaryDirectory function generates a random directory name and creates a new directory in the specified parent directory (or the system's temporary directory if no parent directory is specified) with that name.
.PARAMETER ParentDirectory
The parent directory in which the temporary directory should be created. If not specified, the system's temporary directory will be used.
.PARAMETER Prefix
The prefix to use for the temporary directory name. If not specified, a random prefix will be generated.
.PARAMETER Suffix
The suffix to use for the temporary directory name. If not specified, a random suffix will be generated.
.EXAMPLE
PS C:\> Get-TemporaryDirectory -ParentDirectory "C:\Temp" -Prefix "mytemp" -Suffix "data"
C:\Temp\mytemp_w3jv5q5w.5zv_data
This example creates a new temporary directory with the name "mytemp_w3jv5q5w.5zv_data" in the "C:\Temp" directory and returns the path of the new directory.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$ParentDirectory,
[Parameter(Mandatory=$false)]
[string]$Prefix,
[Parameter(Mandatory=$false)]
[string]$Suffix
)
try {
if ($ParentDirectory) {
if (-not (Test-Path $ParentDirectory -PathType Container)) {
throw "Parent directory '$ParentDirectory' does not exist."
}
$tempPath = $ParentDirectory
} else {
$tempPath = [System.IO.Path]::GetTempPath()
}
if (-not $Prefix) {
$prefix = [System.IO.Path]::GetRandomFileName()
}
if (-not $Suffix) {
$suffix = [System.IO.Path]::GetRandomFileName()
}
do {
$directoryName = "{0}_{1}.{2}" -f $prefix, [System.IO.Path]::GetRandomFileName(), $suffix
$directoryPath = Join-Path $tempPath $directoryName
} while (Test-Path $directoryPath)
New-Item -ItemType Directory -Path $directoryPath | Out-Null
return Get-Item $directoryPath
} catch {
Write-Error "An error occurred while creating the temporary directory: $_"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment