PowerShellを使ってファイルをZIP圧縮する方法をご存じですか?Windows環境では、GUIを使わずにPowerShellのコマンドを活用することで、手軽にファイルを圧縮・解凍できます。特に、Compress-Archive コマンドは、シンプルな記述で複数のファイルをZIP形式に圧縮できる便利な機能です。本記事では、PowerShellのCompress-Archiveコマンドの基本から応用までを徹底解説し、具体的な使用例を紹介します。
Compress-Archive は、PowerShellに標準で搭載されているZIP圧縮用のコマンドレットです。ファイルやフォルダーを圧縮し、拡張子「.zip」のアーカイブファイルを作成できます。
Compress-Archive -Path <圧縮するファイルまたはフォルダーのパス> -DestinationPath <作成するZIPファイルのパス> -Path:圧縮対象のファイルまたはフォルダーを指定。-DestinationPath:作成するZIPファイルのパスを指定。-CompressionLevel:圧縮レベル(Optimal、Fastest、NoCompression)を指定。-Force:既存のZIPファイルを上書きする。Compress-Archive -Path C:\Users\User\Documents\sample.txt -DestinationPath C:\Users\User\Documents\archive.zip このコマンドを実行すると、sample.txt が archive.zip に圧縮されます。
Compress-Archive -Path C:\Users\User\Documents\file1.txt, C:\Users\User\Documents\file2.txt -DestinationPath C:\Users\User\Documents\archive.zip 複数のファイルを一つのZIPファイルにまとめる場合は、カンマ区切りで複数のパスを指定します。
Compress-Archive -Path C:\Users\User\Documents\MyFolder -DestinationPath C:\Users\User\Documents\archive.zip フォルダーを指定すると、そのフォルダー内のすべてのファイルがZIPに圧縮されます。
Compress-Archive では、-CompressionLevel オプションを使って圧縮レベルを変更できます。
Compress-Archive -Path C:\Users\User\Documents\MyFolder -DestinationPath C:\Users\User\Documents\archive.zip -CompressionLevel Optimal 利用可能な圧縮レベル:
Optimal(デフォルト):バランスの取れた圧縮Fastest:最速で圧縮NoCompression:圧縮せずZIP化Compress-Archive コマンドは既存のZIPファイルにファイルを追加できません。ただし、以下の回避策を使用できます。
Expand-Archive -Path C:\Users\User\Documents\archive.zip -DestinationPath C:\Users\User\Documents\TempFolder
Compress-Archive -Path C:\Users\User\Documents\TempFolder\*,C:\Users\User\Documents\newfile.txt -DestinationPath C:\Users\User\Documents\archive.zip -Force この方法では、一度ZIPファイルを展開し、新しいファイルを追加した後に再圧縮します。
既存のZIPファイルをそのまま上書きするには、-Force オプションを使用します。
Compress-Archive -Path C:\Users\User\Documents\MyFolder -DestinationPath C:\Users\User\Documents\archive.zip -Force ZIPファイルを展開する場合は、Expand-Archive コマンドを使用します。
Expand-Archive -Path C:\Users\User\Documents\archive.zip -DestinationPath C:\Users\User\Documents\ExtractedFolder デフォルトでは、Expand-Archive は既存のファイルを上書きしません。上書きする場合は -Force オプションを追加します。
Expand-Archive -Path C:\Users\User\Documents\archive.zip -DestinationPath C:\Users\User\Documents\ExtractedFolder -Force PowerShellのスクリプトを作成することで、複数のファイルやフォルダーを自動的に圧縮することができます。
$sourceFolder = "C:\Users\User\Documents\ToCompress"
$zipFile = "C:\Users\User\Documents\Backup.zip"
Compress-Archive -Path "$sourceFolder\*" -DestinationPath $zipFile -Force このスクリプトを定期的に実行すれば、フォルダーのバックアップを自動化できます。
$date = Get-Date -Format "yyyyMMdd"
$sourceFolder = "C:\Users\User\Documents\ToCompress"
$zipFile = "C:\Users\User\Documents\Backup_$date.zip"
Compress-Archive -Path "$sourceFolder\*" -DestinationPath $zipFile -Force PowerShellのCompress-Archive コマンドを活用すれば、GUIを使わずに簡単にZIP圧縮ができます。特に、スクリプトと組み合わせることで、定期的なバックアップや自動圧縮の仕組みを構築できるのが大きなメリットです。本記事で紹介した基本操作から応用テクニックまでを活用し、PowerShellでのZIP管理を効率的に行いましょう!