Validating file name input in Powershell

时间:2016-04-04 16:29:14

标签: regex powershell

I would like to validate input for file name and check if it contains invalid characters, in PowerShell. I had tried following approach, which works when just one of these character is entered but doesn't seem to work when a given alpha-numeric string contains these characters. I believe I didn't construct regex correctly, what would be the right way to validate whether given string contains these characters? Thanks in advance.

#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"}

2 个答案:

答案 0 :(得分:8)

I would use Path.GetInvalidFileNameChars() rather than hardcoding the characters in a regex pattern, and then use the String.IndexOfAny() method to test if the file name contains any of the invalid characters:

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
    }
}

and then:

$filename = "\?filename.txt"
if(Test-ValidFileName $filename)
{
    Write-Host "$filename is valid"
}
else
{
    Write-Host "$filename contains invalid characters"
}

If you don't want to define a new function, this could be simplified as:

if($filename.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1)
{
    Write-Host "$filename is valid"
}
else
{
    Write-Host "$filename contains invalid characters"
}

答案 1 :(得分:1)

To fix the regex:

Try removing the ^ and $ which anchor it to the ends of the string.