4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Windows 圧縮コマンド(Powershell)いろいろ

Last updated at Posted at 2021-03-11

Windows 圧縮コマンド何通りかやったけど制約が多い。。。
Powershell の標準 Compress-Archive だと2GB以上のファイルあるとエラー。。。
いくつか試したけど他プロセスで使ってるファイルは圧縮するとエラー出てしまう。。。
圧縮前にコピーしてそれに対して圧縮すればよいけどサイズ大きいとつらいかも。。。

Shell. Application 利用

サイズの制約がなく追加もできるので使い勝手はよさそう
ただ非同期実行になるので終了待ち、エラーハンドリングが難しい。。

$filepath = "C:\aaa\bbb\ccc\ddd";
$zipfilepath = "C:\aaa\bbb\ccc\ddd_" + $(Get-Date -Format "yyyyMMddHHmmss") + ".zip";
$cnt = 0;

set-content $zipfilepath ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18 ));
(dir $zipfilepath).IsReadOnly = $false;

$shellApplication = New-Object -com Shell.Application;
$zipPackage = $shellApplication.NameSpace($zipfilepath);

foreach($file in $(Get-ChildItem $filepath)){
    if ($(Get-ChildItem $file.Fullname).Count -eq 0) {
        # 0件のフォルダはエラー発生するのでスキップ
    } else {
        $zipPackage.CopyHere($file.Fullname)
        while(($cnt + 1) -ne $zipPackage.Items().Count) {
            start-sleep -milliseconds 500
        }
        $cnt ++
    }
}

System.IO.Compression.FileSystem CreateFromDirectory

ディレクトリ圧縮のみ使える、サイズ2GB以上がディレクトリにあっても圧縮できる
終了待ち、エラーハンドリングはやりやすい

$filepath = "C:\aaa\bbb\ccc\ddd";
$zipfilepath = "C:\aaa\bbb\ccc\ddd_" + $(Get-Date -Format "yyyyMMddHHmmss") + ".zip";

Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory(
    $filepath
    , [System.IO.Compression.CompressionLevel]::Optimal
    , $false);

System.IO.Compression.FileSystem CreateEntryFromFile

ファイル圧縮のみ使える、サイズ2GB以上だと圧縮できない。。。

$filepath = "C:\aaa\bbb\ccc\ddd.txt";
$zipfilepath = "C:\aaa\bbb\ccc\ddd_" + $(Get-Date -Format "yyyyMMddHHmmss") + ".zip";

Add-Type -AssemblyName System.IO.Compression.FileSystem

$zip = [System.IO.Compression.ZipFile]::Open($zipfilepath, "Update")
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFIle($zip, $filepath, $(Split-Path $filepath -Leaf))
$zip.Dispose();
4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?