Removing Illegal File Name Characters

by Jun 19, 2009

If you have to batch-process tons of file names, you may want to make sure all file names are legal and automatically remove all illegal characters. Here is how you can do that:

$file = "this*file\is_illegal<>.txt"
$file
$pattern = "[{0}]" -f ([Regex]::Escape([String] `
[System.IO.Path]::GetInvalidFileNameChars()))
$newfile = [Regex]::Replace($file, $pattern, '')
$newfile