如何在PowerShell中检查文件名是否包含[a-z] [A-Z] [0-9] -_#。!@以外的字符

时间:2018-02-20 18:28:03

标签: regex powershell

我从几个文件夹中获取文件名,然后我必须检查传入的文件名是否有效。 我必须允许这些字符(Alphabets Numerics - _#。!@)以任何顺序出现。

我有一个PowerShell脚本,我要处理文件名,但在处理之前我需要检查文件名是否只包含这些(上面)字符,否则我会在控制台上记录一条消息,说“文件名无效。”

$Regex = <Need this>
$clientFiles = Get-ChildItem $path | Select-Object FullName, Name, CreationTime 
foreach($cFile in $clientFiles){    
    if ($cFile."Name" -match $Regex){
        #Further process
    }
    else{
        #Dont want to process and will log message here
    }
}

2 个答案:

答案 0 :(得分:3)

要检查字符串输入是否与以下字符串[a-z] [A-Z] [0-9] -_#。!@不匹配,请使用正则表达式[^-a-zA-Z0-9_#.!@]+

注意事项:内部字符类总是放在 - 首先,否则 - 被视为字符类中的元字符。 ^否定了字符类的内容。

如果文件名是该行中唯一的字符串,则使用^[^-a-zA-Z0-9_#.!@]+$。 ^和$添加到正则表达式的行边界。

$regex = "[^-a-zA-Z0-9_#.!@]+"
$fileName = "invalidData++"
If($fileName -match $regex){echo "Invalid File name '$fileName'"}

答案 1 :(得分:0)

这将全部返回为True

$reg = "[a-zA-Z0-9\\#\\.\\!\\_]"
$test1 = "a9z!"
$test2 = "@.!"
$test3 = "r0YUH#"

$test1 -match $reg
$test2 -match $reg
$test3 -match $reg