Filenames with a space

Overview

It’s common to see file names with one or more spaces when the using Microsoft Operating System. The following note shows how these spaces can be removed using PowerShell should the need arise.

List all files with a space:


Get-ChildItem | Where-Object {$_.name -match ' '}

In my example, the following files are listed:


    Directory: C:\junk

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        17/01/2013     21:21         11 filename with a space.txt
-a---        17/01/2013     21:06         11 gash file.txt

Of course, if it’s just pdf files you want to sort out, then the syntax will be:

Get-ChildItem *.pdf | Where-Object {$_.name -match ' '}

To rename these files replacing the space with an underscore character, execute the following code:


Get-ChildItem |
   Where-Object {$_.name -match ' '} |
   Rename-Item -NewName {$_.name -replace '\s+', '_'}

The file names are now:


-a---        17/01/2013     21:21         11 filename_with_a_space.txt
-a---        17/01/2013     21:36         11 gash_file.txt

If you want to remove the spaces without replacing with another character, then the parameters to the Rename-Item cmdlet becomes:


Rename-Item -NewName {$_.name -replace '\s+', ''}

See also

Rename-Item

Using the Where-Object Cmdlet

Get-ChildItem

Advertisements
This entry was posted in powershell and tagged , . Bookmark the permalink.

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