powershellbatch-filepowershell-v5.1

Batch rename and copy multiple files in Windows


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

I want to rename them to:

Then copy them to a new folder like this:

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?

Thanks


Solution

  • Sample tree before

    > tree /f
        myPic_fr.png
        myPic_gr.png
        myPic_it.png
    

    running this script:

    ## Q:\Test\2018\10\11\SO_52760856.ps1
    Get-ChildItem *_*.png | Where-Object BaseName -match '^.*_([^_]{2})$' | 
      ForEach-Object {
        $Country=$Matches[1]
        $NewName=$_.BaseName+"_1080"+$_.Extension
        $_ | 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
    │
    ├───fr
    │       myPic_fr_1080.png
    │
    ├───gr
    │       myPic_gr_1080.png
    │
    └───it
            myPic_it_1080.png