下载后自动打开ZIP文件内容

时间:2019-04-03 20:13:35

标签: windows batch-file cmd

我正在尝试编写一个批处理文件,一旦下载了zip文件,该文件将由filewatcher执行。下载后,将使用相同名称解压缩该文件,然后删除该zip文件,仅保留文件夹和单个PDF文件。我只需要命令就可以对已解压缩的同一文件完成此操作。

7z x -oC:\Users\"user"\Downloads\* C:\Users\"user"\Downloads\*.zip

del C:\Users\"user"\Downloads\*.zip

"command opening the file in the unzipped folder"

exit

2 个答案:

答案 0 :(得分:0)

使用 FOR ,如果您有多个zip文件,它将遍历它们。

@echo off
for %%I in ("%UserProfile%\Downloads\*.zip") do (
    "%ProgramFiles%\7-Zip\7z.exe" e -aoa "-o%%~dpI" -y -- "%%I"
    if not errorlevel 1 (
        del "%%I"
        if exist "%%~dpnI.pdf" start "" "%%~dpnI.pdf"
    )
)

此脚本说,这是下载路径。对于此路径中的每个PDF,请先解压缩然后删除该zip,然后打开所有已解压缩的PDF。

答案 1 :(得分:0)

@echo off
setlocal

:: Start in this dir.
cd /d "%userprofile%\Downloads" || exit /b 1

:: Dir where 7z extracts to.
set "extractdir=unzip_tmp"

:: Zips move here if files or folders exist in cd.
set "faildir=unzip_fail"

rem Continue only if zip files exist.
if not exist *.zip (
    echo No zip files
    exit /b 0
)

for %%A in (*.zip) do (
    set "fail="

    rem Unzip with 7z.
    echo Unzip:  "%%~nxA"
    7z x -o"%extractdir%" "%%~nxA" >nul

    if not errorlevel 1 (
        pushd "%extractdir%" && (

            rem Check if files or folders exist in parent dir.
            for /f "delims=" %%B in ('dir /b') do (
                if exist  "..\%%~B" (
                    echo Exist: "..\%%~B"
                    set "fail=defined"
                )
            )

            rem Open PDF file.
            for /r %%B in (*.pdf) do (
                echo Open:   "%%~nxB"
                start "" /wait "%%~fB"
            )

            rem Move files or folders to parent dir.
            if not defined fail for /f "delims=" %%B in ('dir /b') do (
                echo Move:   "%%~B"
                move "%%~B" .. >nul
            )

            popd
        )

        rem Cleanup.
        if defined fail (
            if not exist "%faildir%" (
                echo Create: "%faildir%"
                md "%faildir%"
            )

            echo Remove: "%extractdir%"
            rd "%extractdir%" /s /q

            echo Move:   "%%~nxA"
            move "%%~nxA" "%faildir%" >nul
        ) else (
            echo Remove: "%%~nxA"
            del "%%~nxA" >nul
        )
    )
)

rem Final cleanup.
if exist "%extractdir%" (
    echo Remove: "%extractdir%"
    rd "%extractdir%" /s /q
)

这使用预设目录将zip文件提取到。 名为extractdir的变量具有要使用的文件夹的名称。 预设目录允许在以下位置搜索PDF文件 孤立的路径。

该脚本非常口头,因此可以查看已解压缩,已移动等内容。

代码操作:

  • 将目录更改为Downloads目录。
  • 如果没有zip文件,则退出。
  • 搜索zip文件。
  • 从zip文件提取到%extractdir%
  • 检查提取的文件和文件夹是否在父目录中。 如果是这样,请将fail设置为defined。
  • 递归搜索PDF文件并打开它们。
  • 如果未定义fail,请将文件和文件夹移动到父目录。
  • 通过删除zip文件或删除%extractdir%进行清理 如果定义失败,则将zip文件移动到%faildir%
  • 最后将%extractdir%删除(如果存在),以免下次运行时出错。