Skip to content

Instantly share code, notes, and snippets.

@m-p-3
Last active November 27, 2024 14:42
Show Gist options
  • Save m-p-3/fd7a91289e7e283e9005b47b85410dde to your computer and use it in GitHub Desktop.
Save m-p-3/fd7a91289e7e283e9005b47b85410dde to your computer and use it in GitHub Desktop.
Little snippet to validate the presence of a directory structure in PowerShell and initialize it if not, along with error handling and optionally verbose output.
function Initialize-Directory {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$path
)
try {
if (-not (Test-Path $path -PathType Container)) {
New-Item -Path $path -ItemType Directory -Force | Out-Null
Write-Verbose "Initialize-Directory: '$path' doesn't exist, creating structure."
} else {
Write-Verbose "Initialize-Directory: '$path' already exists, Skipping creation."
}
return $true
} catch {
Write-Warning "Initialize-Directory: Failed to create ditectory structure at '$path'. Error: $_"
return $false
}
}
if ($MyInvocation.InvocationName -eq $MyInvocation.MyCommand.Name) {
param(
[Parameter(Mandatory)]
[$string]$path
)
Initialize-Directory -Path $path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment