Checking File Names for Invalid Characters

by Jun 16, 2009

File names may not contain certain characters because they are illegal and cannot be processed by Windows. First, let's find out which characters are considered to be illegal in a file name. Use the System.IO.Path .NET class and its GetInvalidFileNameChars() method to get that list:

[System.IO.Path]::GetInvalidFileNameChars()

Depending on the font you are using in your console, not all characters may be displayed correctly. That is OK, because next we want to use the characters to test file names entered by users.

For that, we need a way to find out whether a string contains any of the illegal characters returned by GetInvalidFileNameChars(). With a little trick, you can convert the characters into a regular expression pattern:

$pattern = "[{0}]" -f ([Regex]::Escape([String] `
[System.IO.Path]::GetInvalidFileNameChars()))

Now, it is easy to detect whether a path contains any of the illegal characters:

"my**file.txt" -match $pattern

Here is how to use this to validate user input:

$pattern = "[{0}]" -f ([Regex]::Escape([String] `
[System.IO.Path]::GetInvalidFileNameChars()))
$prompt = 'Enter a file name'
do {
$path = Read-Host $prompt
$wrong = $path -match $pattern
$prompt = "This file name contained '$($matches[0])' " +
"which is illegal in a file name. Try again"
} while ($wrong)

You should note how the script uses the $matches automatic variable to retrieve the actual character that was found to be illegal.