繁体   English   中英

是否可以使用 powershell 提取/读取 zip 中的文件的一部分?

[英]Is it possible to extract / read part of a file within a zip using powershell?

我有一个 powershell 4.0 脚本,它执行各种操作以跨内部网络组织一些大型 zip 文件。 这一切都很好,但我希望做出一些改进。 我想做的一件事是提取 ZIP 文件中 XML 文件中的一些细节。

我通过仅提取运行良好的 XML 对一些小的 ZIP 文件进行了测试。 我针对特定文件是因为 zip 可以包含数千个可能非常大的文件。 这在我的测试文件上运行良好,但是当我扩展测试时,我意识到这并不是特别理想,因为我正在阅读的 XML 文件本身可能会变得非常大(一个约为 5GB,但它们可能会更大)。 因此,向链中添加文件提取步骤会对该过程造成不可接受的延迟,我需要找到替代方法。

理想情况下,我可以从 ZIP 中的 XML 文件中读取 3-5 个值,而无需提取它。 这些值在文件中总是相对较早,所以也许可以只提取文件的前 100kb,我可以将提取物视为文本文件并找到所需的值?

这是否可能/比仅提取整个文件更有效?

如果我不能加快速度,我将不得不考虑另一种方式。 我对文件内容的控制有限,因此可能会考虑在创建 ZIP 时将这些细节拆分为一个较小的单独文件。 不过,这将是最后的手段。

您应该能够使用System.IO.Compression.ZipFile class 执行此操作:

# import the containing assembly
Add-Type -AssemblyName System.IO.Compression.FileSystem

try{
  # open the zip file with ZipFile
  $zipFileItem = Get-Item .\Path\To\File.zip
  $zipFile = [System.IO.Compression.ZipFile]::OpenRead($zipFileItem.FullName)

  # find the desired file entry
  $compressedFileEntry = $zipFile.Entries |Where-Object Name -eq MyAwesomeButHugeFile.xml

  # read the first 100kb of the file stream:
  $buffer = [byte[]]::new(100KB)
  $stream = $compressedFileEntry.Open()
  $readLength = $stream.Read($buffer, 0, $buffer.Length)
}
finally{
  # clean up
  if($stream){ $stream.Dispose() }
  if($zipFile){ $zipFile.Dispose() }
}

if($readLength){
  $xmlString = [System.Text.Encoding]::UTF8.GetString($buffer, 0, $readLength)
  # do what you must with `$xmlString` here :)
}
else{
  Write-Warning "Failed to extract partial xml string"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM