我有很多要解压缩的RAR或ZIP存档。一些档案包含一个文件夹,其中所有文件都位于该文件夹中。其他一些归档文件的所有文件都位于根级别。
案例01
Archive01.rar
MyFolder
file01.txt
file02.txt
file03.txt
etc.
案例02
Archive02.rar
-file01.txt
-file02.txt
-file031.txt
etc.
我知道如何将所有存档提取到一个子文件夹中。
但是,仅当存档中不存在子文件夹时,才如何创建子文件夹?
我的意思是在用于处理数千个存档的批处理过程中,如果存档文件属于案例01,则在提取时不应另外创建文件夹。但是,如果存档文件属于案例02,则应使用存档文件名将其提取到一个子文件夹中。
案例01的结果
MyFolder <- Folder
file01.txt
file02.txt
file03.txt
etc.
案例02的结果
Archive02 <-Folder base on the archive name
-file01.txt
-file02.txt
-file031.txt
etc.
家用机版Rar.exe
有命令l
,以列表根据文本文件的归档文件的内容Rar.txt
在Program Files文件夹的WinRAR的是控制台版本的手册。可以在批处理文件中处理Rar.exe
使用命令l
(或L
)运行时输出的列表,以确定RAR存档文件是否仅在顶层仅包含一个目录,而没有其他内容。但是仅Rar.exe
支持免费的UnRAR.exe
RAR存档。
要同时支持ZIP归档文件,必须使用WinRAR.exe
支持提取RAR和ZIP归档文件以及其他一些归档文件类型的GUI版本。
手册WinRAR.exe
是WinRAR的帮助,可以在运行WinRAR的菜单项“帮助”主题上单击菜单“帮助”来打开。在“帮助”选项卡的“目录”上有一个列表项“命令行模式”,其中包含从命令行运行的参考帮助页面中的所有必要信息。WinRAR.exe
可以看出在寻找上的列表命令是WinRAR.exe
不支持的命令l
,以输出存档文件的内容,因为是一个图形用户界面应用程序控制台窗口。
因此,实际上不可能从命令行或在批处理文件中确定存档文件是否仅在使用时包含顶级目录WinRAR.exe
。
但是,这并不重要,因为先解析存档文件中的文件和目录名称,然后使用适当的命令来提取存档文件,而无需或在命令行上指定额外的提取文件夹,效率会很低。
首先仅使用一个WinRAR调用并使用switch-ad
来提取所有* .rar(然后再提取所有* .zip)文件,将每个存档文件提取到具有存档文件名称的子目录中,然后消除每个提取目录,则效率更高。这是必要的,因为相应的存档文件在顶层仅包含一个目录。
在下面的批处理文件中使用了这种智能方法,该文件包含以下附加功能,使其有望对许多WinRAR用户有用:
可以将工作目录指定为调用批处理文件(甚至可以是UNC路径)时的第一个参数。
对于未在默认程序文件目录中安装WinRAR.exe
32位或64位WinRAR的用例(如在我的所有计算机上),该批处理文件会自动查找在何处安装。
注意:下面发布的批处理批处理文件不会检查当前目录或指定目录中是否已经提取了现有存档文件。因此,建议不要在一个目录中多次运行批处理文件,而一旦处理完归档文件后,该文件就不会从该目录中删除。
@echo off
rem Change working directory if batch file was started with an argument.
if not "%~1" == "" (
pushd "%~1" 2>nul
if errorlevel 1 (
echo Specified directory "%~1" does not exist.
echo/
pause
goto :EOF
)
)
setlocal EnableExtensions DisableDelayedExpansion
rem Does WinRAR exist in default program files folder?
set "WinRAR=%ProgramFiles%\WinRAR\WinRAR.exe"
if exist "%WinRAR%" goto StartExtraction
rem Does WinRAR exist in default program files folder for x86 applications?
set "WinRAR=%ProgramFiles(x86%\WinRAR\WinRAR.exe"
if exist "%WinRAR%" goto StartExtraction
rem Try to determine installation location of WinRAR.exe from registry.
set "TypeToken=2"
goto GetPathFromRegistry
rem On Windows Vista and later REG.EXE outputs without version info:
rem HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe
rem (Default) REG_SZ Full path to WinRAR\WinRAR.exe
rem There are only spaces used to separate value name, value type and value string.
rem But REG.EXE version 3.0 outputs on Windows XP with version info:
rem ! REG.EXE VERSION 3.0
rem
rem HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe
rem <NO NAME> REG_SZ Full path to WinRAR\WinRAR.exe
rem NOTE: There are 4 indent spaces and 2 separating tabs in REG 3.0 output line.
rem So either token 2 or token 3 contains value type REG_SZ
rem used to identify the line with the wanted information.
:GetPathFromRegistry
for /F "skip=1 tokens=%TypeToken%*" %%A in ('%SystemRoot%\System32\reg.exe QUERY "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe" /ve 2^>nul') do (
if "%%A" == "REG_SZ" (
if exist "%%~fB" (
set "WinRAR=%%~fB"
goto StartExtraction
)
) else if "%%A" == "NAME>" (
set "TypeToken=3"
goto GetPathFromRegistry
)
)
endlocal
if not "%~1" == "" popd
echo Could not determine directory containing WinRAR.exe.
echo/
echo Please configure it manually in file: %~f0
echo/
pause
goto :EOF
rem WinRAR supports multiple archive types on extraction.
rem Specify here the archive file extensions for extraction.
:StartExtraction
for %%I in (rar zip) do call :ExtractArchives %%I
rem Restore previous command environment, restore previous current directory
rem and exit this batch file without fall through to the subroutines below.
endlocal
if not "%~1" == "" popd
goto :EOF
rem The subroutine ExtractArchives processes all archive files in current
rem directory with the file extension passed to subroutine as first argument.
rem WinRAR is called once to extract all files with specified file extension
rem for extraction into a subdirectory with name of the archive file.
rem Then one more subroutine is called for each archive file to determine
rem if it is safe to move the extracted archive file contents up one level.
:ExtractArchives
if not exist "*.%~1" goto :EOF
"%WinRAR%" x -ad -cfg- -ibck -y -- "*.%~1"
for %%A in ("*.%~1") do call :MoveUpExtracted "%%~nA"
goto :EOF
rem The subroutine MoveUpExtracted first checks if for the archive file
rem passed to the subroutine as first argument a subdirectory exists at
rem all, i.e. the extraction before was successful for that archive.
rem Next it counts the subdirectories in the archive extraction directory.
rem Nothing is moved up if there is more than 1 subdirectory in archive
rem extraction directory.
rem Also nothing is moved up if archive extraction directory contains
rem 1 or more files.
rem After verification of archive extraction directory really containing
rem only a single subdirectory and nothing else, the name of the archive
rem extraction directory is compared case-insensitive with the name of
rem the single subdirectory in archive extraction directory. On equal
rem directory names the archive extraction directory is renamed by
rem appending _tmp to make it possible to move the subdirectory with same
rem name up one level in directory hierarchy. There is hopefully by chance
rem never a directory present in current directory with name of an archive
rem file and _tmp appended.
rem Next it is checked if in current directory there is not already existing
rem a directory with name of the subdirectory from extracted archive in which
rem case it is also not possible to move the directory up one level. In this
rem special use case the archive extraction directory is kept containing just
rem a single subdirectory with restoring original directory name.
rem Then the single subdirectory in archive extraction directory is moved up
rem one level which is very fast as just the file allocation table is updated
rem and no data is really moved.
rem The directory movement could fail if the extracted directory has hidden
rem attribute set. In this case temporarily remove the hidden attribute,
rem move the directory up one level in directory hierarchy and set the
rem hidden attribute again on the directory.
rem On a succesful moving up of the extracted directory the (renamed)
rem extraction directory being now empty is deleted as not further needed.
:MoveUpExtracted
if not exist "%~1\" (
echo Error: No folder for archive %~1
goto :EOF
)
echo Processing archive folder "%~1"
set FolderCount=0
set "FolderName="
for /F "delims=" %%D in ('dir "%~1\*" /AD /B 2^>nul') do (
if defined FolderName goto :EOF
set /A FolderCount+=1
set "FolderName=%%D"
)
if not %FolderCount% == 1 goto :EOF
for /F "delims=" %%F in ('dir "%~1\*" /A-D /B 2^>nul') do goto :EOF
set "ParentRenamed=0"
set "ParentFolder=%~1"
if /I "%~1" == "%FolderName%" (
ren "%~1" "%~1_tmp" 2>nul
if errorlevel 1 (
echo Failed to rename "%~1" to "%~1_tmp".
goto :EOF
)
set "ParentFolder=%~1_tmp"
set "ParentRenamed=1"
)
if exist "%FolderName%" (
if %ParentRenamed% == 1 ren "%~1_tmp" "%~1"
echo Error: Folder exists "%FolderName%"
goto :EOF
)
move "%ParentFolder%\%FolderName%" "%FolderName%" >nul 2>nul
if not errorlevel 1 (
rd "%ParentFolder%"
goto :EOF
)
%SystemRoot%\System32\attrib.exe -h "%ParentFolder%\%FolderName%" >nul
move "%ParentFolder%\%FolderName%" "%FolderName%" >nul
if errorlevel 1 (
if %ParentRenamed% == 1 (
ren "%ParentFolder%" "%~1"
goto :EOF
)
)
%SystemRoot%\System32\attrib.exe +h "%FolderName%"
rd "%ParentFolder%"
goto :EOF
从Windows 95开始,我就使用32位Windows,但我从未遇到过MAX_PATH
限制,即绝对文件/文件夹名称长于259个字符。
因此,当存档文件名非常长(例如,文件名+文件扩展名恰好为256个字符)时,重写批处理文件以使其正常工作是一个非常有趣并且非常耗时的挑战。
在下面的批处理文件开发过程中,我发现以下内容:
有些命令(例如DIR,FOR,RD和REN)在路径AND文件/文件夹名称中支持短8.3名称,而其他命令(例如ATTRIB和MOVE)仅在路径中支持它们,而在文件/文件夹名称中则不支持(至少在Windows XP中)。
因此,无法使用其简短的8.3名称移动文件夹或更改其属性。
当具有完整路径的文件夹名称长于259个字符时,所有命令均无法仅使用具有相对文件夹路径的相对文件夹名称。这意味着Windows命令解释器在执行任何命令之前首先确定具有完整路径的文件夹名称。因此,当前目录在处理名称非常长的存档或包含名称非常长的目录时应该具有较短的路径。
我无法弄清楚如何获得一个文件夹的短名称或者使用其路径%~fs1
,通过解释call /?
或%%~fsI
(批处理文件),通过解释for /?
时,只是一个相对的文件夹路径是由Windows命令解释器解析,即只长一个文件夹的名称没有它的道路。
在运行命令DIR并带有/X
获取目录短名称的选项时,第三列包含短名称,第四列包含长名称。但是在非常短的文件夹名称中,第三列的简称可能会丢失。
dir /AD /X
在NTFS分区上执行的英语Windows 7 SP1 x64的输出,在Windows区域和语言设置中设置了德国:
Volume in drive C is System
Volume Serial Number is 7582-4210
Directory of C:\Temp\Test
29.04.2017 22:39 <DIR> .
29.04.2017 22:39 <DIR> ..
29.04.2017 22:39 <DIR> ARCHIV~1 archive_with_a_very_very_very_..._long_name_1
29.04.2017 22:39 <DIR> Batch
29.04.2017 22:39 <DIR> xyz
dir /AD /X
在FAT32分区上的德语Windows XP SP3 x86上执行的命令相同,并且在Windows区域和语言设置中设置了德语:
Datenträger in Laufwerk F: ist TEMP
Volumeseriennummer: CAA5-41AA
Verzeichnis von F:\Temp
29.04.2017 22:39 <DIR> .
29.04.2017 22:39 <DIR> ..
29.04.2017 22:39 <DIR> BATCH Batch
29.04.2017 22:39 <DIR> xxx
29.04.2017 22:39 <DIR> ARCHIV~1 archive_with_a_very_very_very_..._long_name_1
注意:我...
在这里用in name截断了很长的目录名称。
为什么目录Batch
在Windows XP计算机上具有短名称,BATCH
但在Windows 7上却没有短名称,这对我来说真的很难解释。
这是批处理脚本,只要当前目录的路径较短,它也支持归档中的长归档名称和长目录名称。
@echo off
rem Change working directory if batch file was started with an argument.
if not "%~1" == "" (
pushd "%~1" 2>nul
if errorlevel 1 (
echo Specified directory "%~1" does not exist.
echo/
pause
goto :EOF
)
)
setlocal EnableExtensions DisableDelayedExpansion
rem Does WinRAR exist in default program files folder?
set "WinRAR=%ProgramFiles%\WinRAR\WinRAR.exe"
if exist "%WinRAR%" goto StartExtraction
rem Does WinRAR exist in default program files folder for x86 applications?
set "WinRAR=%ProgramFiles(x86%\WinRAR\WinRAR.exe"
if exist "%WinRAR%" goto StartExtraction
rem Try to determine installation location of WinRAR.exe from registry.
set "TypeToken=2"
goto GetPathFromRegistry
rem On Windows Vista and later REG.EXE outputs without version info:
rem HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe
rem (Default) REG_SZ Full path to WinRAR\WinRAR.exe
rem There are only spaces used to separate value name, value type and value string.
rem But REG.EXE version 3.0 outputs on Windows XP with version info:
rem ! REG.EXE VERSION 3.0
rem
rem HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe
rem <NO NAME> REG_SZ Full path to WinRAR\WinRAR.exe
rem NOTE: There are 4 indent spaces and 2 separating tabs in REG 3.0 output line.
rem So either token 2 or token 3 contains value type REG_SZ
rem used to identify the line with the wanted information.
:GetPathFromRegistry
for /F "skip=1 tokens=%TypeToken%*" %%A in ('%SystemRoot%\System32\reg.exe QUERY "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe" /ve 2^>nul') do (
if "%%A" == "REG_SZ" (
if exist "%%~fB" (
set "WinRAR=%%~fB"
goto StartExtraction
)
) else if "%%A" == "NAME>" (
set "TypeToken=3"
goto GetPathFromRegistry
)
)
endlocal
if not "%~1" == "" popd
echo Could not determine directory containing WinRAR.exe.
echo/
echo Please configure it manually in file: %~f0
echo/
pause
goto :EOF
rem WinRAR supports multiple archive types on extraction.
rem Specify here the archive file extensions for extraction.
rem But first delete temporary folder from a previous breaked execution.
:StartExtraction
rd /Q /S # 2>nul
for %%I in (rar zip) do call :ExtractArchives %%I
rem Restore previous command environment, restore previous current directory
rem and exit this batch file without fall through to the subroutines below.
endlocal
if not "%~1" == "" popd
goto :EOF
rem The subroutine ExtractArchives processes all archive files in current
rem directory with the file extension passed to subroutine as first argument.
rem WinRAR is called once to extract all files with specified file extension
rem for extraction into a subdirectory with name of the archive file.
rem Then one more subroutine is called for each archive file to determine
rem if it is safe to move the extracted archive file contents up one level.
:ExtractArchives
if not exist "*.%~1" goto :EOF
"%WinRAR%" x -ad -cfg- -ibck -y -- "*.%~1"
for %%A in ("*.%~1") do call :MoveUpExtracted "%%~nA" %1
goto :EOF
rem The subroutine MoveUpExtracted first checks if for the archive file
rem passed to the subroutine as first argument a subdirectory exists at
rem all, i.e. the extraction before was successful for that archive, and
rem determines short 8.3 name of this directory.
rem Next it counts the subdirectories in the archive extraction directory
rem using short directory name. Nothing is moved up if there is more than
rem 1 subdirectory in archive extraction directory.
rem Also nothing is moved up if archive extraction directory contains
rem 1 or more files.
rem After verification of archive extraction directory really containing
rem only a single subdirectory and nothing else, the current archive folder
rem is renamed to # (single character folder name) using short folder name.
rem This folder rename should work in general. The current archive folder
rem is kept in case of this folder rename fails unexpected because it is
rem not yet known if the current directory does not already contain the
rem single directory extracted from current archive or rename failed
rem because of a permission or a directory sharing access restriction.
rem Next it is checked if in current directory there is not already existing
rem a directory with name of the subdirectory from extracted archive in which
rem case it is also not possible to move the directory up one level. In this
rem special use case the archive extraction directory is kept containing just
rem a single subdirectory with restoring original directory name. In case of
rem restoring archive directory fails unexpected, the directory with name #
rem is deleted and the archive is extracted once again into a directory with
rem name of archive file.
rem It is clear on this point that the single directory in archive extraction
rem directory can be moved up to current directory from directory wit having
rem now the temporary name #.
rem Moving a directory with command MOVE is not possible if hidden attribute
rem is set on directory. For that reason it is checked next if the directory
rem to move up has hidden attribute set using its short directory name.
rem In case of directory has hidden attribute is indeed set, it is removed
rem which is also verified. The verification can't be done with errorlevel
rem evaluation as external command ATTRIB does not set errorlevel on failed
rem attribute change. So the attribute check is done once again after the
rem hidden attribute is removed with ATTRIB.
rem ATTRIB also fails to change the attribute if absolute folder path is
rem longer than 259 characters. In this case the current extraction folder
rem with temporary name # is deleted completely and the current archive is
rem extracted once again to current directory without creation of an
rem additional directory with name of archive file.
rem Then the single subdirectory in archive extraction directory having
rem now name # is also renamed to # using short directory name to avoid
rem a problem on next command MOVE with an absolute folder path longer
rem than 259 characters as much as possible.
rem The directory extracted from archive with name # in directory # is
rem moved up to current directory with suppressing all errors which could
rem occur for example if path of current directory plus name of directory
rem as extracted from archive file is too long.
rem The directory # in current directory with its subdirectory # is deleted
rem on a moving error and the current archive file is extracted once again
rem into current directory without creation of an additional directory with
rem name of archive file.
rem But on successful movement of the folder with correct name to current
rem directory the hidden attribute is set on folder if the extracted folder
rem has it also set before moving the folder and the finally empty folder #
rem is deleted before exiting subroutine.
:MoveUpExtracted
set "FolderToCheck=%~f1"
set "FolderToCheck=%FolderToCheck:~0,258%"
for /F "skip=5 tokens=4*" %%X in ('dir "%FolderToCheck%*" /AD /X 2^>nul') do (
if "%%Y" == "%~1" set "ArchiveFolder=%%X" & goto Subfolders
if "%%Y" == "" if /I "%%X" == "%~1" set "ArchiveFolder=%%X" & goto Subfolders
)
echo Error: No folder for archive %~1
goto :EOF
:Subfolders
@echo off
echo Processing archive folder "%~1"
set FolderCount=0
set "FolderName="
for /F "delims=" %%D in ('dir "%ArchiveFolder%\*" /AD /B 2^>nul') do (
if defined FolderName goto :EOF
set /A FolderCount+=1
set "FolderName=%%D"
)
if not %FolderCount% == 1 goto :EOF
for /F "delims=" %%F in ('dir "%ArchiveFolder%\*" /A-D /B 2^>nul') do goto :EOF
ren "%ArchiveFolder%" # 2>nul
if errorlevel 1 (
echo Error: Failed to rename "%~1"
goto :EOF
)
set "FolderToCheck=%~dp1%FolderName%"
set "FolderToCheck=%FolderToCheck:~0,258%"
for /F "skip=5 tokens=4*" %%X in ('dir "%FolderToCheck%*" /AD /X 2^>nul') do (
if "%%Y" == "%FolderName%" goto FolderExist
if "%%Y" == "" if /I "%%X" == "%FolderName%" goto FolderExist
)
set "HiddenFolder=0"
set "FolderToCheck=%~dp1#\%FolderName%"
set "FolderToCheck=%FolderToCheck:~0,258%"
for /F "skip=5 tokens=4*" %%X in ('dir "%FolderToCheck%*" /AD /X 2^>nul') do (
if "%%Y" == "%FolderName%" set "FolderToMove=%%X" & goto CheckHidden
if "%%Y" == "" if /I "%%X" == "%FolderName%" set "FolderToMove=%%X" & goto CheckHidden
)
:CheckHidden
for %%X in ("#\%FolderToMove%") do (
for /F "tokens=2 delims=h" %%H in ("%%~aX") do (
if %HiddenFolder% == 1 goto ArchiveExtract
set "HiddenFolder=1"
%SystemRoot%\System32\attrib.exe -h "#\%FolderName%"
goto CheckHidden
)
)
ren "#\%FolderToMove%" # 2>nul
move #\# "%FolderName%" >nul 2>nul
if errorlevel 1 goto ArchiveExtract
if %HiddenFolder% == 1 %SystemRoot%\System32\attrib.exe +h "%FolderName%"
rd #
goto :EOF
:ArchiveExtract
rd /Q /S #
"%WinRAR%" x -cfg- -ibck -y -- "%~1.%~2"
goto :EOF
:FolderExist
echo Error: Folder exists "%FolderName%"
ren # "%~1" 2>nul
if not errorlevel 1 goto :EOF
rd /Q /S #
"%WinRAR%" x -ad -cfg- -ibck -y -- "%~1.%~2"
goto :EOF
最好用C或C ++或C#编写控制台应用程序,因为它可以替换MoveUpExtracted
上述批处理脚本中的子例程,因此具有长路径意识。
在Windows 10版本1607(周年更新)或更高版本的Windows上MAX_PATH
,可以通过组策略或通过添加注册表值来禁用260个字符(259个字符加上终止空字节)的限制,请参阅
为了了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。
attrib /?
call /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
move /?
pause /?
popd /?
pushd /?
rd /?
reg /?
reg query /?
rem /?
ren /?
set /?
setlocal /?
另请阅读Microsoft文章:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句