Search code examples
powershellrename

Removing part of filename


I am trying to remove part of a filename after a specific character. I have had a look around but can't seem to find a suitable answer. Each filename is unique expect for a - in the middle.

Current Filenames;

somefilename - somefilenamewithmore
somefilename123 - somefilenamewithmore123
somefilename5555 - somefilenamewithmore5555

What I want it to be;

somefilename 
somefilename123 
somefilename5555 


Fore reference files are located in C:\users\%username%\rename

I have found plenty of info on removing a specific number of characters or removing something specific from the filename, but not having any luck trying to remove everything after a certain character.

Any help/pointers would greatly be appreciated


Solution

  • Get-ChildItem C:\users\$env:username\rename -file | foreach {
      Rename-Item -Path $_.FullName -NewName ($_.Name.Split(' ')[0]) }
    

    Optionally, if there's an extension (like .pdf or whatever) you can edit that to:

    Rename-Item -Path $_.FullName -NewName ($_.Name.Split(' ')[0] + $_.Extension)
    

    Also, I'm not sure if you want the current username, so I've originally left your path untouched, but people edited that part out, perhaps it makes more sense this way, I'm not sure ;)