Batch rename and copy multiple files in Windows

Wadjey Source

I have a large number of files with names like this in a same folder:

  • myPic_fr.png
  • myPic_it.png
  • myPic_gr.png

I want to rename them to:

  • myPic_fr_1080.png
  • myPic_it_1080.png
  • myPic_gr_1080.png

Then copy them to a new folder like this:

  • ../fr/myPic_fr_1080.png
  • ../it/myPic_it_1080.png
  • ../gr/myPic_gr_1080.png

How to create a batch script or powershell script to do that job?

Edit: I tried this batch script code to do the rename job (Thanks @RoXX):

@echo off
setlocal EnableDelayedExpansion
SET oldPart=.png
SET newPart=_1080.png
for /f "tokens=*" %%f in ('dir /b *.png') do (
  SET newname=%%f
  SET newname=!newname:%oldPart%=%newPart%!
  move "%%f" "!newname!"

But for the "copy" part I don't know how to do it! Maybe need Regex?




answered 6 days ago Razorfen #1

This is far from optimal, but you could try something like this:

foreach ($pic in (Get-ChildItem *.png -Name)) {
    # delete "myPic_" and ".png" to get the destination-folder from the filename
    $destFolder = ($pic -replace "myPic_", "") -replace "`.png", ""
    # replace ".png" with "_1080.png" to create the new filename
    $destName = $pic -replace ".png", "_1080.png"

    Copy-Item "$pic" "$destFolder\$destName"

answered 6 days ago LotPings #2

Sample tree before

> tree /f

running this script:

## Q:\Test\2018\10\11\SO_52760856.ps1
Get-ChildItem *_*.png | Where-Object BaseName -match '^.*_([^_]{2})$' | 
  ForEach-Object {
    $_ | Rename-Item -NewName $NewName
    if (!(Test-Path $Country)){MD $Country|Out-Null}
    Copy-Item  $NewName (Join-Path $Country $newName)  

and the tree after

> tree /f
│   myPic_fr_1080.png
│   myPic_gr_1080.png
│   myPic_it_1080.png
│       myPic_fr_1080.png
│       myPic_gr_1080.png

answered 6 days ago Esperento57 #3

try this

Get-ChildItem "C:\temp\test" -file -Filter "?*_?*.png" | %{

$NewName="{0}_1080{1}" -f $_.BaseName, $_.Extension
$NewDir="{0}\{1}" -f $_.DirectoryName, ($_.BaseName -split "_")[-1]
$NewPath="{0}\{1}" -f $NewDir, $NewName

New-Item $NewDir -ItemType Directory -Force
Copy-Item $_.FullName -Destination $NewPath -Force -Recurse
Rename-Item $_.FullName -NewName $NewName

comments powered by Disqus