将文件或文件夹放在同一个蝙蝠上时备份文件或文件夹

Backup a File or Folder when dropping it on the same bat

所以我设法拼凑了一个脚本 在使用“复制”时可以按预期用于文件。它会创建一个备份文件夹“_OLD”,并通过检查备份文件夹中的最高版本来制作我放在蝙蝠上的文件的迭代(file001、file002 等)副本。我多么希望只有一个蝙蝠能够以相同的方式处理文件或文件夹。通过用“xcopy”替换“copy”,我设法复制了文件夹,但现在文件根本不会被复制。我知道一点编程,但我对 bat 脚本不是很有经验。是否有一种简单的修复方法可以使其在文件和文件夹上的工作相同?

@echo off
rem set this to whatever you like
set "BackupFolderName=_OLD"

rem splits filename into name and extension etc for processing
set "OutputFolder=%CD%\%BackupFolderName%"
set "FullPath=%~1"
set "Filename=%~n1"
set "Ext=%~x1"

rem creates an output folder if none exist
if not exist "%OutputFolder%" mkdir "%OutputFolder%"

rem find the highest version of the file
set a=1
set pad=00000

:loop
rem leading zeroes
SET b=%pad%%a%
rem %var:~10% gets the sub-string from index 10 to the end of %var%
SET b=%b:~-3%
if exist "%OutputFolder%\%Filename%%b%%Ext%" set /a a+=1 && goto :loop

echo "Backed up %FilenameExt% as %Filename%%b%%Ext% in %BackupFolderName%"
xcopy /s/y "%FullPath%" "%OutputFolder%\%Filename%%b%%Ext%"


rem pause
timeout 1 >nul
exit

这是我的最终代码,它获取多个文件或文件夹并对其进行备份:

@echo off
setlocal

rem set this output folder name to whatever you like eg _OLD
set "BackupFolderName=_OLD"
rem creates an output folder, if none exist
set "OutputFolder=%CD%\%BackupFolderName%"
if not exist "%OutputFolder%" mkdir "%OutputFolder%"

rem loops through all the files dropped on bat
FOR %%G IN (%*) DO (call :sub %%G)
goto :end

:sub
rem splits filename into name and extension etc for processing
set "FullPath=%~1"
set "Filename=%~n1"
set "Ext=%~x1"


rem rem find the highest version of the file
set a=1
set pad=00000

:loop
rem leading zeroes
SET b=%pad%%a%
rem %var:~10% gets the sub-string from index 10 to the end of %var%
SET b=%b:~-3%
if exist "%OutputFolder%\%Filename%%b%%Ext%" set /a a+=1 && goto :loop


rem rem checks if dropped item is file or folder
set type=invalid
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"d" >nul && set type=folder)
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"-" >nul && set type=file)

rem copies file or folder to destination
if %type%==file (copy "%FullPath%" "%OutputFolder%\%Filename%%b%%Ext%" >nul)
if %type%==folder (xcopy /s/y/q "%FullPath%" "%OutputFolder%\%Filename%%b%%Ext%\" >nul)

echo "Backed up %Filename% as %Filename%%b%%Ext% in %BackupFolderName%"
goto :eof

:end
pause
rem timeout 1 >nul
rem exit

您可以检查文件属性(参见for /?

@echo off
setlocal

set type=invalid
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"d" >nul && set type=folder)
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"-" >nul && set type=file)
echo %type%