【问题标题】:Create / Extract zip file and overwrite existing files/content创建/提取 zip 文件并覆盖现有文件/内容
【发布时间】:2018-01-18 23:48:13
【问题描述】:
Add-Type -A System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory('foo', 'foo.zip')
[IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', 'bar')

我从answer 中找到了通过 PowerShell 创建和提取 .zip 文件的代码,但由于我的声誉低,我无法提出问题作为对该答案的评论。

  • 创建 - 如何在没有用户交互的情况下覆盖现有的 .zip 文件?
  • 提取 - 如何在没有用户交互的情况下覆盖现有文件和文件夹? (最好喜欢robocopysmir函数)。

【问题讨论】:

  • documentation 告诉你什么?
  • 您使用的是哪个版本的 PowerShell?如果您使用5.0 或更高版本,Compress-Archive 是更好的选择。

标签: powershell


【解决方案1】:

PowerShell 5 之前的版本可以执行this script

感谢@Ola-M 提供更新。

感谢@maximilian-burszley 提供更新。

function Unzip($zipfile, $outdir)
{
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $archive = [System.IO.Compression.ZipFile]::OpenRead($zipfile)
    try
    {
        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);
            }
        }
    }
    finally
    {
        $archive.Dispose()
    }
}

Unzip -zipfile "$zip" -outdir "$dir"

【讨论】:

  • 一些资源没有被释放,因为我得到“Copy-Item : The process cannot access the file 'my.zip' because it is being used by another process.”
  • 我添加了一行来修复它 ($archive.Dispose())
  • 一个建议:包装在 try/finally 中,并在 finally 中处理托管资源,这样即使某些东西是 SIGINTed,它们也会被释放。
【解决方案2】:

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


压缩:

Compress-Archive -Path C:\Foo -DestinationPath C:\Foo.zip -CompressionLevel Optimal -Force

还有一个-Update 开关。

解压:

Expand-Archive -Path C:\Foo.zip -DestinationPath C:\Foo -Force

【讨论】:

  • 这些仅在 PS 5.0 中添加,因此可能不适用,具体取决于 OP 使用的版本。它们当然是处理 zip 文件的最简单方法。
  • 感谢@JamesC 的留言。该详细信息未显示在帮助内容中。
  • 我有 PowerShell 5。非常感谢!
  • 如何强制压缩隐藏文件和文件夹?
  • @Yethat 如果-Force 参数不起作用,您可能需要编写逻辑以在压缩之前/之后隐藏/取消隐藏文件夹。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
相关资源
最近更新 更多