简体   繁体   English

用 powershell 读取 zip 文件

[英]Read zip file with powershell

is there any faster way to filter a zip file?有没有更快的方法来过滤 zip 文件? My code reads the file line by line, so the data loads very slowly.我的代码逐行读取文件,因此数据加载非常缓慢。 Can I filter more than one line at a time?我可以一次过滤多行吗?

$ZipPath = 'C:\Test\TestZip.zip'
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)
$eachlinenumber = 1
while (($readeachline = $reader.ReadLine()) -ne $null)
{
    
    $x = select-string -pattern "Order1" -InputObject $readeachline 
    Add-Content C:\text\TestFile.txt $x
}  

$reader.Close()
$stream.Close()
$zip.Dispose()

The issue with your code is not because you're reading the content line-by-line, the actual issue is due to appending to a file on each loop iteration.您的代码的问题不是因为您正在逐行阅读内容,实际问题是由于在每次循环迭代时附加到文件。 I assume you're looking to have all lines matching Order1 from your Zip Entry added to TestFile.txt , in which case you should consider using a StreamWriter in combination with the StreamReader .我假设您希望将 Zip 条目中与Order1匹配的所有行都添加到TestFile.txt中,在这种情况下,您应该考虑将StreamWriterStreamReader结合使用。 This will keep the File Stream opened while iterating over each line.这将使文件 Stream 在遍历每一行时保持打开状态。

try {
    Add-Type -AssemblyName System.IO.Compression.Filesystem

    $zipPath = 'C:\Test\TestZip.zip'
    $zipFile = [IO.Compression.ZipFile]::OpenRead($ZipPath)
    $zipEntry = $zipFile.Entries[0]
    $entryStream = $zipEntry.Open()
    $reader = [IO.StreamReader]::new($entryStream)
    $writer = [IO.StreamWriter]::new('C:\text\TestFile.txt')

    while (-not $reader.EndOfStream) {
        if(($line = $reader.ReadLine()) -match 'Order1') {
            $writer.WriteLine($line)
        }
    }
}
finally {
    $reader, $writer, $entryStream, $zipFile | ForEach-Object Dispose
}

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

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