简体   繁体   中英

move files from one folder to another and if exists rename

I am trying to find a solution to move all files, all types of extensions,from source folder to destination folder.

The problem is the scripts I found online are not checking if there are already files with the same name in destination folder and if it's the case to add the underscore and a variable number(1,2,3,4,5 and so on) at the end of the file.

I have something here that I tried to put together but it's not working. Batch script or Powershell doesn't matter. The requested outcome is to move all files and if file a.pdf exists in destination folder, move it to destination folder and add a variable number a_1.pdf or a_2.pdf

@ECHO OFF
SETLOCAL
SET "sourcedir=C:\Users\Daniel\Desktop\testing"
SET "destdir=C:\Users\Daniel\Desktop\testing2"
FOR /f "delims=" %%a IN (
 'dir /s /b /a-d "%sourcedir%\*" '
 ) DO (
 IF EXIST "%destdir%\%%~nxa" (
  SET notfound=Y
  FOR /L %%b IN (1,1,999) DO IF DEFINED notfound IF NOT EXIST "%destdir%\%%~na(%%b)%%~xa" (
   (move "%%a" "%destdir%\%%~na(%%b)%%~xa"
   SET "notfound="
  )
  IF DEFINED notfound ECHO(Failed to COPY "%%a"
 ) ELSE ((move "%%a" "%destdir%\%%~nxa"
 )
)

pause

actual outcome it this

move "C:\Users\Daniel\Desktop\testing\1.jpeg" "C:\Users\Daniel\Desktop\testing2\1(1).jpeg"
move "C:\Users\Daniel\Desktop\testing\1.txt" "C:\Users\Daniel\Desktop\testing2\1(1).txt"

but when I look in the folder, nothing happens

Many thanks

@ECHO Off
SETLOCAL
SET "sourcedir=C:\Users\Daniel\Desktop\testing"
SET "destdir=C:\Users\Daniel\Desktop\testing2"

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"

FOR /f "delims=" %%a IN (
 'dir /s /b /a-d "%sourcedir%\*" '
 ) DO (
 IF EXIST "%destdir%\%%~nxa" (
  rem destfile exists
  echo destfile "%destdir%\%%~nxa" exists
  SET "notfound=Y"
  FOR /L %%b IN (1,1,999) DO IF DEFINED notfound IF NOT EXIST "%destdir%\%%~na(%%b)%%~xa" (
   move "%%a" "%destdir%\%%~na(%%b)%%~xa"
   SET "notfound="
  )
  IF DEFINED notfound ECHO Failed to COPY "%%a"
 ) ELSE (
  rem destfile does not exist
  echo destfile "%destdir%\%%~nxa" does NOT EXIST
  move "%%a" "%destdir%\%%~nxa" >nul
 )
)
GOTO :eof

This worked for me. Frankly, I'm too tired to work out the differences.

Notes:
I overrode the directoryname values.
I added rems and step-by-step reporting, which obviously could be removed
Caution: code executes move statements as posted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM