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:
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:
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 path'
$path = Read-Host $prompt
$prompt = 'Path was illegal. Try again'
} while ($path -match $pattern)