5

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 Answers 2

16

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
    return $IndexOfInvalidChar -eq -1
}

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

If desired, a regular expression pattern could be created like this: '[{0}]' -f [regex]::Escape(([IO.Path]::GetInvalidFileNameChars() -join ''))
1

To fix the regex:

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

1 Comment

Removing the ^ and $ fixed it. Mathias approach using GetInvalidFileNameChars() looks good/worked as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.