/ / Try / catch para caracteres ilegais - PowerShell, tratamento de erros, try-catch, caracteres ilegais

Tente / pegar para caracteres ilegais - powershell, tratamento de erros, try-catch, caracteres ilegais

Problema e detalhes

Estou trabalhando com o tratamento de erros personalizado e umUm dos erros que estou tendo dificuldade em capturar é o "Caracteres ilegais no caminho". Eu tenho uma função personalizada que visa procurar na cadeia de caracteres esses caracteres ilegais e gera um erro personalizado quando eles são encontrados. Mas estou descobrindo que, dependendo do caráter ilegal, o Test-Path O cmdlet lança o erro primeiro.

Eu tentei coisas como:

try {
Test-Path $path
} catch {
"Custom Message"
}

O que meio que fará o que eu quero ... mas não totalmente.

function isPathValid {
[CmdletBinding()]
Param(
[Parameter]
[string]$path
)
if (!($path -match "[^a-zA-Zs]") -OR ($path -match "[^<>*?`"```|]") {
throw "customException"
} else {
return $true
}
}

O que realmente não funciona ... mas se eu mudar a segunda parte para combinar com eles individualmente, eu posso pegar a maioria.

Questão

É possível criar um -match verificar caracteres como `<> *? | "` `? Ou existe uma maneira mais intuitiva de capturar esses personagens?

Supondo que o acima é possível, existe uma maneira de garantir que eu possa usá-lo para capturar o problema antes que o Test-Path o cmdlet faz?

Respostas:

2 para resposta № 1

Você pode continuar usando Test-Path com o IsValid interruptor

$path = "C:PathToValidFile.extension"
$isPathValid = Test-Path -Path $path -IsValid # True

$path = "C:InvalidPath<>"
$isPathValid = Test-Path -Path $path -IsValid # False

$path = "C:Path?ValidFileName"
$isPathValid = Test-Path -Path $path -IsValid # False

$path = "C:InvalidPathInvalidFileName?"
$isPathValid = Test-Path -Path $path -IsValid # False

ou potencialmente usar Path.GetInvalidPathChars ou PathGetInvalidFileNameChars / incorporar em sua própria validação

$path = "C:PathToValidFile.extension"
$isPathValid = $path.IndexOfAny([System.IO.Path]::GetInvalidPathChars()) -lt 0 # True

$path = "C:InvalidPath<>"
$isPathValid = $path.IndexOfAny([System.IO.Path]::GetInvalidPathChars()) -lt 0 # False

# Note difference between this return compared to Test-Path above
$path = "C:Path?ValidFileName"
$isPathValid = $path.IndexOfAny([System.IO.Path]::GetInvalidPathChars()) -lt 0 # True

$path = "C:Path?ValidFileName"
$isPathValid = $path.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -lt 0 # False

$path = "C:InvalidPathInvalidFileName?"
$isPathValid = $path.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -lt 0 # False