Checking Paths for Invalid Path Characters

by Jun 15, 2009

Paths 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 path. To get that list, use the System.IO.Path .NET class and its GetInvalidPathChars() method:

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

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 paths entered by users.

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

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

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

"c:test><" -match $pattern

Here is how to use this to validate user input:

$pattern = "[{0}]" -f ([Regex]::Escape([String] `
[System.IO.Path]::GetInvalidPathChars()))
$prompt = 'Enter a path'
do {
$path = Read-Host $prompt
$prompt = 'Path was illegal. Try again'
} while ($path -match $pattern)