I'm looking to validate some file paths if passed in to the script and I was wondering which is the preferred/cleanest in order to level up my scripting?
In the process block?
# Validate the csvPath parameter is a valid path and ends with a trailing slash
if ($PSBoundParameters.ContainsKey('csvPath')) {
try {
Test-Path -Path $csvPath -PathType Container
}
catch {
throw "The path defined in $csvPath is not valid. An example of a working path is C:\temp\"
}
if (-not $csvPath.EndsWith("\")) {
$csvPath += "\"
}
}
or is it better in the param declaration itself?
[Parameter(Position=2,
Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
HelpMessage="Desired full path for output, a valid path looks like C:\temp\")]
[ValidateScript( {
if (-not (Test-Path -Path $_ -PathType Container)) {
throw "The path defined in $_ is not valid. An example of a working path is C:\temp\"
}
if (-not $_.EndsWith("\")) {
$_ += "\"
}
return $_
})]
[string]$csvPath = "$(Get-Location)\"
Or is there an even better way I should look for?