Batch rename files according to file names in another folder with powershell

I have a large number of files in a folder named "01-aaa-bbb-ccc", "02-ddd-eee-fff", etc. In another folder, I have an earlier version of the same files without an index (which was added manually to sort them in a specific order) "aaa-bbb-ccc", "ddd-eee-fff". I would like to use an earlier version, but I need to rename them by adding the same index as in another folder.

Basically, something like: rename the files in folder b in the same way as onse in folder a if the file name without an index matches.

Is there a way to do this in PowerShell? Unfortunately, my skills are not good enough for this. Thanks for the help!

+3
source share
3

. :

$newNames = Get-ChildItem ..\a -Name
# Cd into b dir
Get-ChildItem | Foreach {$name = $newNames -match "\d+-$_";if ($name){$_}} | 
                Rename-Item -NewName {$name}
+2
$ht = @{}
Get-ChildItem a\* | Select-Object -ExpandProperty name | ForEach-Object {
  $null = $_ -match '(\d+)-(.*)'
  $ht[$Matches[2]] = $Matches[1]
}
Get-ChildItem b\* | ForEach-Object { Rename-Item $_ ($ht[$_.name] + '-' + $_.name) }

-, . b .

+1
Get-ChildItem .\a\* | Select -Expand Name | %{ $_ -match "([\d]+)-(.+)" }  | `
%{ Rename-Item -WhatIf .\b\$($matches[2]) $matches[0] }
0
source

All Articles