Check File Names for Illegal Characters

by Oct 27, 2016

File names are quite sensitive and may not contain a number of reserved characters. To validate file names and make sure they are legal, here is a slight adaption of yesterday’s script (which checked file system paths). This one checks file names for validity:

# check path:
$filenameToCheck = 'testfile:?.txt'

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

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

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

And here is the result:

 
Do not use these characters in file names: : ?

Twitter This Tip! ReTweet this Tip!