1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

バッチファイルで7z圧縮する(7zipを使用)

Last updated at Posted at 2021-05-05

Y子です。
今日は、ファイルを7z形式に圧縮してみます。
細かい仕様は、Zip圧縮のときを踏襲します。

概要

7zipを使って、7z形式に圧縮します。
自動処理の中で使用することを想定します。
7zipの実行ファイルは、通常インストールで配置されるC:\Program Files\7-Zip\7z.exeを使っています。
確認環境:Windows 10 Home (Bld. 19042.928)

コード

(1) 1ファイルを圧縮する

7zip_compress_s2s.bat
@echo off
setlocal

set exe="C:\Program Files\7-Zip\7z.exe"

rem 引数がない場合は終了する
if "%~1"=="" (echo 引数がありません & pause & exit /b)

rem 圧縮前ファイル
set str_file=%~1

rem 圧縮後ファイル
set str_zipfile=%str_file%.7z

rem zip圧縮実行
call %exe% a "%str_zipfile%" "%str_file%"
echo %str_zipfile%

endlocal
pause
実行結果
> 7zip_compress_s2s.bat "C:\work dir\test01.txt"
7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive:
1 file, 1890 bytes (2 KiB)

Creating archive: C:\work dir\test01.txt.7z

Add new data to archive: 1 file, 1890 bytes (2 KiB)


Files read from disk: 1
Archive size: 165 bytes (1 KiB)
Everything is Ok
C:\work dir\test01.txt.7z
続行するには何かキーを押してください . . .

(2)複数ファイルをひとつに圧縮する

7zip_compress_m2s.bat
@echo off
setlocal

set exe="C:\Program Files\7-Zip\7z.exe"

rem 日付「20210402」形式
set str_date=%date:~0,4%%date:~5,2%%date:~8%

rem 時刻「094617」形式
set str_time=%time: =0%
set str_time=%str_time:~0,2%%str_time:~3,2%%str_time:~6,2%

rem 圧縮前ファイル(初期化)
set str_file=

rem 圧縮後ファイル
set str_zipfile=%~dp1
set str_zipfile=%str_zipfile%7zfile_%str_date%_%str_time%.7z

rem 引数がない場合は最後に飛んで終了する
if "%~1"=="" (
  goto :label_end
)

rem zip圧縮実行
call %exe% a "%str_zipfile%" %*
echo %str_zipfile%

:label_end
echo 処理を終了しました
endlocal
pause
実行結果
> 7zip_compress_m2s.bat "C:\work dir\dir1" "C:\work dir\test01.txt" "C:\work dir\test02.txt"

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive:
1 folder, 4 files, 10425 bytes (11 KiB)

Creating archive: C:\work dir\7zfile_20210505_234727.7z

Add new data to archive: 1 folder, 4 files, 10425 bytes (11 KiB)


Files read from disk: 4
Archive size: 5025 bytes (5 KiB)
Everything is Ok
C:\work dir\7zfile_20210505_234727.7z
処理を終了しました
続行するには何かキーを押してください . . .

おわりに

7zipは、zipより圧縮率が高く、アプリとしても完成度が高いので、半ば標準化している感じがしますね。
パスワード付きや自動解凍書庫も、そのうちバッチ化してみたいです。

では!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?