powershell recursive rename with wildcard

I have these backup files:
Social_DB_backup_2018_01_07_071010_0794131.BAK
SharePoint_Config_backup_2018_01_07_071010_0326524.bak
BDC_Service_DB_backup_2018_01_07_071010_0482393.bak
 And so on....
I want to rename them
Social_DB_backup.bak
SharePoint_Config_backup.bak
BDC_Service_DB.bak
how can I go recursively through file directory and rename all of the backups?
Thanks!
dkochenoAsked:
Who is Participating?
 
oBdACommented:
Depends. In the first two examples, you kept the "_backup" part and only removed the dates, in the BDC example, you removed the _backup as well ...

Both of the following are in test mode and will only show which files they would rename how; remove the -WhatIf argument to run them for real:
To keep the "_backup":
Get-ChildItem -Filter *.bak -Recurse |
	Where-Object {$_.BaseName -match '(?<NewName>.*)_\d{4}_\d{2}_\d{2}_\d{6}_\d{7}'} |
	ForEach-Object {Rename-Item -Path $_.FullName -NewName "$($Matches['NewName'])$($_.Extension)" -WhatIf}

Open in new window


To remove the "_backup" as well:
Get-ChildItem -Filter *.bak -Recurse |
	Where-Object {$_.BaseName -match '(?<NewName>.*)_backup_\d{4}_\d{2}_\d{2}_\d{6}_\d{7}'} |
	ForEach-Object {Rename-Item -Path $_.FullName -NewName "$($Matches['NewName'])$($_.Extension)" -WhatIf}

Open in new window

0
 
Dustin SaundersDirector of OperationsCommented:
Critera = only remove numbers from end?  

What should happen if there are more than 1 file that would rename to the same?
0
 
Dustin SaundersDirector of OperationsCommented:
No feedback from Author, but code provided sufficient.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.