Checking Paths and Files for Illegal Characters

by Apr 21, 2016

In the previous tip we illustrated how you can get a list of characters that are illegal in paths or file names. However, what would be the best and easiest way to check whether any of these characters actually existed in a given path or file name?

Simply use the -cnotmatch operator. Here are two functions that test whether paths and file names contain illegal characters. They also show how to encode ASCII codes of illegal characters in a RegEx-compliant way:

function Test-PathName ($Path)
    $invalidPath = -join [System.IO.Path]::GetInvalidPathChars().Foreach{('\x{0:x2}' -f ([Byte][Char]$_))}
    $Path -cnotmatch "[$invalidPath]"

function Test-FileName($Path)
    $invalidName = -join [System.IO.Path]::GetInvalidFileNameChars().Foreach{('\x{0:x2}' -f ([Byte][Char]$_))}
    $Path -cnotmatch "[$invalidName]"

Test-PathName -Path "c:\this\is\ok"
Test-PathName -Path "c:\this|is\notok"
Test-FileName -Path "ok.txt"
Test-FileName -Path "not:ok.txt"

Twitter This Tip! ReTweet this Tip!