【问题标题】:PowerShell extract folder content from zipPowerShell 从 zip 中提取文件夹内容
【发布时间】:2018-11-29 02:23:28
【问题描述】:

我有多个文件夹,假设它们是Folder1, Folder2, Folder3, etc. 在每个人的内部都有.zip 文件命名为文件夹名称。所以Folder1.zip, Folder2.zip, Folder3.zip, etc. 在每个拉链里面都有path 就像Content/1/a/5/t/ZIPNAME/a/b/c/temp。除了 ZIPNAME 是当前迭代的 zip 之外,路径是相同的。 temp 文件夹包含我需要复制到新创建的文件夹中的文件,例如 .zip 名称。我怎样才能做到这一点?

这是我目前得到的。遍历每个文件夹,获取 zip 并打开它。如何从 zip 文件中获取内容并将其复制到新文件夹?

    Set-Location -Path $(BaseDeployPath)
    Add-Type -AssemblyName System.IO.Compression.FileSystem

    Get-ChildItem -Recurse -Directory | ForEach-Object {
          $zipPath = Get-ChildItem $_.FullName -Filter *.zip
          $zip = [System.IO.Compression.ZipFile]::OpenRead($zipPath)

          $contentPath = ???

          $zip.Entries | Get-Content $contentPath
    }

    # close ZIP file
    $zip.Dispose()
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    请查看文档。 OpenRead() 方法返回一个ZipArchive 对象,其Entries 属性包含ZipArchiveEntry 对象的集合。这些对象(除其他外)有一个属性FullName,其中包含存档中项目的相对路径,因此您应该能够像这样选择要处理的文件:

    $temp = 'Content/1/a/5/t/ZIPNAME/a/b/c/temp/'
    
    $zip = [IO.Compression.ZipFile]::OpenRead($zipPath)
    $entries = $zip.Entries | Where-Object { $_.FullName.StartsWith($temp) -and $_.Name }
    

    附加子句-and $_.Name 从结果中排除目录条目(具有空的Name 属性)。

    该文档还列出了一种方法ExtractToFile(),据称它允许将条目提取到文件中。但是,该方法在我的测试箱上不可用。不确定它是在 PowerShell 中不可用,还是在 .Net 框架的更新版本中添加。

    不过,您可以用老式的方式提取文件:

    $entries | ForEach-Object {
        $dstPath = Join-Path 'C:\destination\folder' $_.Name
    
        $src = $_.Open()
        $dst = New-Object IO.FileStream $dstPath, 'Create', 'Write', 'Read'
        $src.CopyTo($dst)
        $src.Close(); $src.Dispose()
        $dst.Close(); $dst.Dispose()
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2016-04-18
      相关资源
      最近更新 更多