Batch file 将文件或文件夹放到同一个bat上时进行备份

Batch file 将文件或文件夹放到同一个bat上时进行备份,batch-file,backup,file-copying,Batch File,Backup,File Copying,因此,我已经设法拼凑出一个脚本,当使用“复制”时,它可以按照文件的预期工作。它创建一个备份文件夹“_OLD”,并通过检查备份文件夹中的最高版本,对我在bat上丢弃的文件进行迭代(file001、file002等)。我多么希望只有一个bat能够以同样的方式处理文件或文件夹。通过用“xcopy”替换“copy”,我成功地复制了文件夹,但现在根本无法复制文件。我懂一点编程,但我对bat脚本不是很有经验。有没有一种简单的方法可以使它在文件和文件夹上都能正常工作 @echo off rem set thi

因此,我已经设法拼凑出一个脚本,当使用“复制”时,它可以按照文件的预期工作。它创建一个备份文件夹“_OLD”,并通过检查备份文件夹中的最高版本,对我在bat上丢弃的文件进行迭代(file001、file002等)。我多么希望只有一个bat能够以同样的方式处理文件或文件夹。通过用“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

您可以检查文件属性(请参见
以获取/?

@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%