我想在PowerShell中验证文件名的输入并检查它是否包含无效字符.我曾尝试过以下方法,当只输入其中一个字符时它会起作用,但当给定的字母数字字符串包含这些字符时似乎不起作用.我相信我没有正确构造正则表达式,验证给定字符串是否包含这些字符的正确方法是什么?提前致谢.
#Validate file name whether it contains invalid characters: \ / : * ? " < > |
$filename = "\?filename.txt"
if($filename -match "^[\\\/\:\*\?\<\>\|]*$")
{Write-Host "$filename contains invalid characters"}
else
{Write-Host "$filename is valid"}
Run Code Online (Sandbox Code Playgroud)
我会使用Path.GetInvalidFileNameChars()而不是硬编码正则表达式模式中的字符,然后使用该String.IndexOfAny()方法来测试文件名是否包含任何无效字符:
function Test-ValidFileName
{
param([string]$FileName)
$IndexOfInvalidChar = $FileName.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars())
# IndexOfAny() returns the value -1 to indicate no such character was found
if($IndexOfInvalidChar -eq -1)
{
return $true
}
else
{
return $false
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
$filename = "\?filename.txt"
if(Test-ValidFileName $filename)
{
Write-Host "$filename is valid"
}
else
{
Write-Host "$filename contains invalid characters"
}
Run Code Online (Sandbox Code Playgroud)
如果您不想定义新函数,可以将其简化为:
if($filename.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1)
{
Write-Host "$filename is valid"
}
else
{
Write-Host "$filename contains invalid characters"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2662 次 |
| 最近记录: |