Home > Mobile >  Optimizing a powershell batch rename script
Optimizing a powershell batch rename script

Time:12-01

I wrote the script below to batch rename files with powershell. It is intended to remove dots (.) and every (-) that is followed by a number from the filenames. Example: text.10-1 becomes text101. However, I feel like there must be a way to do this in a line of code. Also, I wanted it to also enter a subdirectory and do it, how do I write it?


Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-1",'1') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-0",'0') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-2",'2') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-3",'3') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-4",'4') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-5",'5') $_.Extension)" }
Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-6",'6') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-7",'7') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-8",'8') $_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-9",'9') $_.Extension)" }```

Thanks

CodePudding user response:

You can do this with a single Get-ChildItem call:

(Get-ChildItem -Path 'D:\Test' -File -Recurse) | Where-Object { $_.BaseName -match '[-.]' } |
Rename-Item -NewName {'{0}{1}' -f ($_.BaseName -replace '[-.] '), $_.Extension} -WhatIf

Note: I have added switch -WhatIf for safety so you can first see what would happen in the console. When you are satisfied with that, remove the -WhatIf switch and run again to actually start renaming the files.

switch -Recurse lets Get-ChildItem also find files in subfolders

CodePudding user response:

How about this? Get-childitem in parens to avoid the "modifying the loop" problem.

echo hi | set-content -1.txt,-2.txt,-3.txt
(get-childitem) | rename-item -newname { $_.name -replace '-(\d)','$1' } -whatif

What if: Performing the operation "Rename File" on target "Item: C:\users\admin\foo\-1.txt Destination: C:\users\admin\foo\1.txt".
What if: Performing the operation "Rename File" on target "Item: C:\users\admin\foo\-2.txt Destination: C:\users\admin\foo\2.txt".
What if: Performing the operation "Rename File" on target "Item: C:\users\admin\foo\-3.txt Destination: C:\users\admin\foo\3.txt".
  • Related