PowerShell: Replacing Invalid Characters in a Filename

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:

 image

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: image

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s