gpt4 book ai didi

powershell - 尝试/捕获非法字符

转载 作者:行者123 更新时间:2023-12-03 08:11:21 26 4
gpt4 key购买 nike

问题与细节

我正在使用自定义错误处理,遇到的错误之一是“路径中的非法字符”。我有一个自定义函数,旨在通过路径字符串查找此类非法字符,并在找到它们时引发自定义错误。但是我发现,取决于非法字符,Test-Path cmdlet首先引发错误。

我已经尝试过类似的事情:

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

哪一种会做我想要的...但不完全。
function isPathValid {
[CmdletBinding()]
Param(
[Parameter]
[string]$path
)
if (!($path -match "[^a-zA-Z\s]") -OR ($path -match "[^\<\>\*\?\`"\``\`|]") {
throw "customException"
} else {
return $true
}
}

这实际上并没有用...但是如果我将第二部分更改为单独与它们匹配,我可以捕获最多的东西。



是否可以为`<> *之类的字符创建 -match检查? | ”?还是有一种更直观的方式来捕获这些字符?

假设上述情况可行,是否有办法确保在 Test-Path cmdlet之前可以使用它来解决问题?

最佳答案

您可以继续通过Test-Path开关使用IsValid

$path = "C:\Path\To\Valid\File.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:\InvalidPath\InvalidFileName?"
$isPathValid = Test-Path -Path $path -IsValid # False

或可能使用 Path.GetInvalidPathCharsPathGetInvalidFileNameChars/合并到您自己的验证中
$path = "C:\Path\To\Valid\File.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:\InvalidPath\InvalidFileName?"
$isPathValid = $path.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -lt 0 # False

关于powershell - 尝试/捕获非法字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com