AdHimself
AdHimself

Reputation: 15

Trim File Name of Trailing White Spaces for Child Items - Powershell

Hopefully someone can help me out.

I currently run a script that cleans up file names by using:

get-childitem -recurse | dir -Filter *.mp4 | Rename-Item -NewName { $_.BaseName.replace('Oldname','NewName') + $_.Extension }

It has a ton of extra words and stuff piped in and works very well. I'm making a new script using this method, but I'm left with a trailing white space at the end of each file.

From what I can see Trim should do what I need:

.Trim()

As I understand it should remove any leading and trailing white spaces.

I was thinking of just removing all white spaces, but the problem with that is some filenames will have multiple words separated by white spaces.

So I thought that a loop may do the trick, but as I'm still new to Powershell I can't quite work it out.

Long story short, I'm looking to run a recursive scan on all files in a directory, specifically MP4 and MKV, then for each file in the directory, apply trim to it so it will remove any trailing white spaces.

Any help with this would be greatly appreciated!


Perfect answer from Doug Maurer. I just needed to add the trim at the end of my commands, I think I was just placing it wrong, then thinking I needed to loop it. The answer is far more simple.

Before anyone says something, I know this isn't the most elegant script, but I does what I need it to. It's used to find specific words in file names, and remove them and replace them with nothing. However, once done, sometimes I'm left with a trailing white space.

By adding trim to the end, before adding the extension back on, it removes the space perfectly for my use case.

get-childitem -recurse | dir -Filter *.mp4 | Rename-Item -NewName { $_.BaseName.replace('Name1','').replace('Name2','').replace('Name3','').replace('Name4','').replace('Name5','').replace('Name6','').replace('Name7','').replace('Name8','').Trim() + $_.Extension }

With Doug's suggested edit of removing DIR as it's unnecessary:

Get-ChildItem -Recurse -Filter *.mp4 | Rename-Item -NewName { $_.BaseName.replace('Name1','').replace('Name2','').replace('Name3','').replace('Name4','').replace('Name5','').replace('Name6','').replace('Name7','').replace('Name8','').Trim() + $_.Extension }

Upvotes: 0

Views: 1004

Answers (1)

Doug Maurer
Doug Maurer

Reputation: 8868

You don't have trim in there so I can't say why your attempts have not worked. What I can say is that you don't need two DIR commands, (dir is alias for Get-ChildItem). It seems your command is missing the part where you add the extension back to the name and the final curly brace. The following will trim the basename like you describe.

Get-ChildItem -Recurse -Filter *.mp4 |
    Rename-Item -NewName {$_.BaseName.replace('Oldname','NewName').Trim() + $_.Extension}

Upvotes: 2

Related Questions