Finding Illegal Characters in Paths (File System)

by Oct 26, 2016

Previously we illustrated how you can use a simple RegEx-based approach to find illegal characters in strings. We encourage you to expand this strategy on all kinds of strings that might need validation.

If you’d like to detect illegal characters in file paths, here is a slight adaption:

# check path:
$pathToCheck = 'c:\test\<somefolder>\f|le.txt'

# get invalid characters and escape them for use with RegEx
$illegal =[Regex]::Escape(-join [System.Io.Path]::GetInvalidPathChars())
$pattern = "[$illegal]"

# find illegal characters
$invalid = [regex]::Matches($pathToCheck, $pattern, 'IgnoreCase').Value | Sort-Object -Unique 

$hasInvalid = $invalid -ne $null
if ($hasInvalid)
{
  "Do not use these characters in paths: $invalid"
}
else
{
  'OK!'
}

The invalid characters are taken from GetInvalidPathChars() and converted into an escaped string that can be used with Regular Expressions. This list is placed into brackets, so RegEx would report if any one of these characters were found.

Here is the result:

 
Do not use these characters in paths: | < >
 

Twitter This Tip! ReTweet this Tip!