【问题标题】:Read Text-File inside ZIP in Powershell在 Powershell 中读取 ZIP 中的文本文件
【发布时间】:2017-08-31 12:50:02
【问题描述】:

我想读取存储在 ZIP 文件中的文本文件。 目前我使用 7Zip 提取所需的文件,阅读它们并再次删除它们。 有没有办法在不将它们提取到硬盘驱动器的情况下读取它们?

【问题讨论】:

    标签: powershell zip


    【解决方案1】:

    tl;博士

    是的,有办法。但是有什么好办法吗? 不,绝对不是。


    有办法。但这在很大程度上取决于您的操作系统。 PowerShell 5 具有 Expand-Archive,这使得使用 7Zip 已过时,但即使使用 Expand-Archive,您也必须提取整个存档才能读取文件的内容。

    使用 Windows 机器,您可以使用 shell.application Com 对象或 system.io.compression.filesystem 来完成它,就像此线程引用的那样:
    How to read contents of a csv file inside zip file using PowerShell

    4.还有一种使用原生方式的方法:

    Add-Type -assembly "system.io.compression.filesystem"
    $zip = [io.compression.zipfile]::OpenRead("e:\E.zip")
    $file = $zip.Entries | where-object { $_.Name -eq "XMLSchema1.xsd"}
    $stream = $file.Open()
    
    $reader = New-Object IO.StreamReader($stream)
    $text = $reader.ReadToEnd()
    $text
    
    $reader.Close()
    $stream.Close()
    $zip.Dispose()
    

    XMLSchema1.xsd 是您的文件名所在的位置。

    链接的答案提到了一些其他方式(主要与外部依赖项和 Windows 操作系统相关联)。他们中的大多数仍然至少提取一个文件,但准确地说:

    【讨论】:

    • @Clijsters 虽然它可能看起来并不完美,但它解决了我的问题和我的另一个问题,所以谢谢你,感谢你引用的帖子的作者!
    【解决方案2】:

    当我使用压缩日志文件时,压缩文件中只有一个文件。

    我做了这个函数来获取日志文件的内容。

    感谢 Andrey Marchuk 和他在下面链接中回答的第 4 点。他的代码是我用来制作这个功能的。 How to read contents of a csv file inside zip file using PowerShell

    function Get-ZippedLog {
        param (
            [Parameter(Mandatory=$true)]$ZipPath
        )
        Add-Type -assembly "system.io.compression.filesystem"
        $zip = [io.compression.zipfile]::OpenRead($ZipPath)
    
        $file = $zip.Entries[0]
        $stream = $file.Open()
    
        $reader = New-Object IO.StreamReader($stream)
        $text = $reader.ReadToEnd()
    
        $reader.Close()
        $stream.Close()
        $zip.Dispose()
    
        return $text
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2020-12-04
      • 1970-01-01
      相关资源
      最近更新 更多