Search code examples
windowsbashpowershellbatch-rename

Change multiple folder name from %-% to % (delete everything after the hyphen)


I have a folder containing multiple sub folders named like : 12345 - textfoldername

I want to rename all these sub folders by keeping just the first number (12345) and delete all the rest ( - textfoldername).

How can I build the windows script for that.

Thanks for your help !


Solution

  • With , use Get-ChildItem to discover all the subfolders, then use Rename-Item to rename:

    Get-ChildItem path\to\root\directory -Directory |Rename-Item -NewName {$_.Name -replace ' - .+$'}
    

    The -replace operator with remove - and anything thereafter in the existing name (or, if - something isn't found, ignore it)