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:
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:
Now, it is easy to detect whether a path contains any of the illegal characters:
Here is how to use this to validate user input:
$prompt = 'Enter a file name'
$path = Read-Host $prompt
$wrong = $path -match $pattern
$prompt = "This file name contained '$($matches)' " +
"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.