LoginSignup
0

More than 1 year has passed since last update.

PowerShell V5で2GBを超えるzipファイル作成

Last updated at Posted at 2022-07-27

PowerShell V5(powershell.exe)でCompress-Archiveコマンドレットでフォルダからzipを作成しようとして以下のようなエラーになった

Compress-Archive : Exception calling "Write" with "3" argument(s): "Stream was too long."
At C:\XXX\XXX.ps1:98 char:3
+   Compress-Archive -Path $dir -DestinationPath $zipFile -Force
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Compress-Archive], MethodInvocationException
    + FullyQualifiedErrorId : IOException,Compress-Archive

上記は以下の2GB制限があるため
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/compress-archive?view=powershell-7#description

The Compress-Archive cmdlet uses the Microsoft .NET API System.IO.Compression.ZipArchive to compress files. The maximum file size is 2 GB because there's a limitation of the underlying API.

PowerShell V7(pwsh.exe)だと以下が使える

[IO.Compression.ZipFile]::CreateFromDirectory($dir, $zipFile)

しかしV5だと上記は以下のエラーになる

Unable to find type [IO.Compression.ZipFile].
At C:\XXX\XXX.ps1:98 char:1
+ [IO.Compression.ZipFile]::CreateFromDirectory($dir, $zipFile ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (IO.Compression.ZipFile:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

V5の場合には事前に以下を実行しておく

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

さらに、上書きエラー回避も入れて以下が完成版

if (Test-Path $zipFile) {
  Remove-Item $zipFile -Force
}
Add-Type -AssemblyName System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory($dir, $zipFile)

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
0