创建/解压缩zip文件并覆盖现有文件/内容

Cla*_*ers 17 powershell

Add-Type -A System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory('foo', 'foo.zip')
[IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', 'bar')
Run Code Online (Sandbox Code Playgroud)

我找到了通过PowerShell从这个答案创建和提取.zip文件的代码,但由于我的声誉很低,我不能问一个问题作为对该答案的评论.

  • 创建 - 如何在没有用户交互的情况下覆盖现有的.zip文件?
  • 提取 - 如何在没有用户交互的情况下覆盖现有文件和文件夹?(最好像robocopys的 mir功能).

The*_*le1 22

PowerShell具有内置.zip实用程序,无需在版本5及更高版本中使用.NET类方法.该Compress-Archive -Path参数还采用一种string[]类型,因此您可以将多个文件夹/文件压缩到目标zip中.


荏苒:

Compress-Archive -Path C:\Foo -DestinationPath C:\Foo.zip -CompressionLevel Optimal -Force
Run Code Online (Sandbox Code Playgroud)

还有一个-Update开关.

解压:

Expand-Archive -Path C:\Foo.zip -DestinationPath C:\Foo -Force
Run Code Online (Sandbox Code Playgroud)

  • 这些仅在PS 5.0中添加,因此可能不适用,具体取决于OP使用的版本。它们无疑是处理zip文件的最简单方法。 (2认同)

yW0*_*K5o 5

5之前的PowerShell版本可以执行此脚本

感谢@ Ola-M进行更新。

function Unzip($zipfile, $outdir)
{
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $archive = [System.IO.Compression.ZipFile]::OpenRead($zipfile)
    foreach ($entry in $archive.Entries)
    {
        $entryTargetFilePath = [System.IO.Path]::Combine($outdir, $entry.FullName)
        $entryDir = [System.IO.Path]::GetDirectoryName($entryTargetFilePath)

        #Ensure the directory of the archive entry exists
        if(!(Test-Path $entryDir )){
            New-Item -ItemType Directory -Path $entryDir | Out-Null 
        }

        #If the entry is not a directory entry, then extract entry
        if(!$entryTargetFilePath.EndsWith("\")){
            [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $entryTargetFilePath, $true);
        }
    }
    $archive.Dispose()
}

Unzip -zipfile "$zip" -outdir "$dir"
Run Code Online (Sandbox Code Playgroud)