I’m currently writing a script that requires me to create folders based on the contents of a CSV-dump from SQL. One thing I need to do is check that each item I’m pulling out of the CSV will translate to a valid Windows folder name.
One easy way to do it is by using the .NET System.IO.Path.GetInvalidFileNameChars() method. This method returns a System.Char array containing all of the characters that can’t be used in a file or folder name. Here’s a sample of the output:
Assuming that the string we wish to interrogate for invalid characters is stored in a variable called $text, we’d use the following one-liner to loop through all of the invalid characters and replace them with another of our choosing. In this case, I’m replacing them with a period.
[System.IO.Path]::GetInvalidFileNameChars() | % {$text = $text.replace($_,'.')}
Here’s a screenshot of it in action: