1

I have a folder with a load of subfolders with a random number at the beginning of their folder name. they are in this format:

1254170-folder1
1212340-folder2
3245417-folder3

What can I to rename all of them to

folder1
folder2
folder3

I tried something like this because I saw something similar about filenames.

for f in *\1*;do( mv "$f" "${f//1/ }");done

but it does not work. the powershell returned

At line:1 char:4
+ for f in *\1*;do( mv "$f" "${f//1/ }");done
+    ~
Missing opening '(' after keyword 'for'.
At line:1 char:17
+ for f in *\1*;do( mv "$f" "${f//1/ }");done
+                 ~
Missing statement body in do loop.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword

Not sure what should I do. I am using Windows 10 2004. Thanks for the help.

Mq Hu
  • 21
  • 3

2 Answers2

2

This should work:

Get-ChildItem -path . -directory -recurse | Where {$_.Name -match '^\d+-'} | Rename-Item -NewName {$_.Name -replace '^\d+-',''}
  • First command enumerates folders and all subfolders in current directory (.).
  • Second command filters folders which starts with digits followed by dash (^\d+- regex)
  • Third command renames the folders by removing ^\d+- prefix
Renat
  • 7,718
  • 2
  • 20
  • 34
0

I complet the @Renat code :

if you want exclude the directories with format without characters after the '-' (example 1254170- )

And if you want your script continue same if a directory with the new name already exist

Get-ChildItem "c:\temp\" -dir | where name -match "^\d+-.+$" | Rename-Item -NewName {$_.Name.Split('-')[1]} -ErrorAction SilentlyContinue
Esperento57
  • 16,521
  • 3
  • 39
  • 45
  • `$_.Name.Split('-')[1]` will not work as intended if the foldername contained two or more dashes though.. – Theo Dec 13 '20 at 11:18