将文件复制到目标文件夹并保留重复项

时间:2017-09-25 03:25:32

标签: batch-file copy xcopy

如何将某个文件复制到已具有相同名称的同一文件的目标文件夹,同时保留这两个文件。

例如。 如果a.jpg已存在于目标文件夹中(假设有一个),那么现在会有两个名称不同的文件(例如a.jpg和a(1).jpg

2 个答案:

答案 0 :(得分:0)

我们也可以使用TIMESTAMP:

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%-%MS%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
Xcopy /s "D:\folder1\test.xls" "D:\folder2\test_%fullstamp%.xls"
pause

答案 1 :(得分:0)

这是每个人都想要的解决方案,但只有少数人会得到(正是那些查找此页面的人)。 @Hackoo,我亲吻你的脚。

创建一个名为easycopy.bat的批处理文件,然后将以下内容放入其中:

@rem easycopy
@rem Usage: easycopy SourcePath TargetPath (SourcePath can be the path to a directory or a single file)
@rem release 24/05/2020
@echo off

setlocal enableDelayedExpansion

rem Initialize and validate arguments
if "%~2" equ "" echo Error: Insufficient arguments>&2&exit /b 1
set "source=%1"
set "target=%2"
set /a counter=0
if not exist %target%\ echo Error: Target folder %target% does not exist>&2&exit /b 1

if not exist %source%\ call :newfile %source% %target% & set /a counter+=1 & goto :end

rem Do the work
for /r %source% %%F in (*) do if "%%~dpF" neq %target%\ (
  if exist %target%\"%%~nxF" (
    call :newfile "%%F" %target% & set /a counter+=1
  ) else copy "%%F" %target% >nul & set /a counter+=1
)

:end
echo.
if %errorlevel% EQU 0 echo %counter% file/s was/were copied.
if %errorlevel% GTR 0 echo Check if something went wrong.
goto :eof

:newfile <Source> <Destination>
set Source=%1
set Destination=%2
set Filename=%~n1
set Extention=%~x1
set a=1
:loop
if not exist %Destination%\"%Filename%%Extention%" copy %Source% %Destination%\"%Filename%%Extention%" >nul & goto :eof
if exist %Destination%\"%Filename%(%a%)%Extention%" set /a a+=1 && goto :loop
copy %Source% %Destination%\"%Filename%(%a%)%Extention%" >nul