Last active
November 27, 2024 14:42
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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