Windows批处理脚本:解压目录中的文件

11

我想解压缩特定目录中的所有文件,并在解压缩时保留文件夹名称。

以下批处理脚本并没有完全实现这一功能。它只是将一堆文件丢在那里,而没有将它们放入文件夹中,甚至无法完成任务。

这里出了什么问题?

for /F %%I IN ('dir /b /s *.zip') DO (

    "C:\Program Files (x86)\7-Zip\7z.exe" x -y -o"%%~dpI" "%%I" 
)

你的压缩文件名中是否有空格?如果是,你的第一行代码应该是:for /F "usebackq" %%I IN (dir /b /s "*.zip") DO ( - RGuggisberg
尝试这个:for /F "delims=" %%I IN ('dir /b /s/a-d *.zip') DO ( - Endoro
5个回答

34

试试这个:

for /R "C:\root\folder" %%I in ("*.zip") do (
  "%ProgramFiles(x86)%\7-Zip\7z.exe" x -y -o"%%~dpI" "%%~fI" 
)

或者(如果你想把文件提取到以Zip文件命名的文件夹中):

for /R "C:\root\folder" %%I in ("*.zip") do (
  "%ProgramFiles(x86)%\7-Zip\7z.exe" x -y -o"%%~dpnI" "%%~fI" 
)

如果我需要将文件提取到不同的目标位置,我该怎么办? - Jibin

7

Ansgar的回答对我来说几乎是完美的,但如果提取成功后我还想删除归档文件。我找到了这个,并将其合并到上面的代码中:

for /R "Destination_Folder" %%I in ("*.zip") do (
  "%ProgramFiles%\7-Zip\7z.exe" x -y -aos -o"%%~dpI" "%%~fI"
  "if errorlevel 1 goto :error"
    del "%%~fI"
  ":error"
)

能否将文件提取到不同的目录中? - Jibin

1
尝试一下。
@echo off
for /F "delims=" %%I IN (' dir /b /s /a-d *.zip ') DO (
    "C:\Program Files (x86)\7-Zip\7z.exe" x -y -o"%%~dpI\%%~nI" "%%I" 
)
pause

@moinkhan 我很乐意帮忙。你哪一部分感到困惑了? - foxidrive
@foxidrive,请解释循环中的参数和整个想法,以及它是如何工作的。 - Mohib

0

你的一些压缩文件名中是否含有空格?如果是,你的第一行应该是:

for /F "usebackq" %%I IN (`dir /b /s "*.zip"`) DO (

请注意使用 ` 而不是 ' 请参阅 FOR /?

使用“delims=”是处理长名称的必要步骤。 - foxidrive

0
作为PowerShell脚本(而且不需要第三方工具),您可以运行以下命令:
#get the list of zip files from the current directory
$dir = dir *.zip
#go through each zip file in the directory variable
foreach($item in $dir)
  {
    Expand-Archive -Path $item -DestinationPath ($item -replace '.zip','') -Force
  }

来自用户'pestell159'在Microsoft论坛上发布的帖子。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接