使用powershell读取zip文件

lf5gs5x2  于 2022-12-29  发布在  Shell
关注(0)|答案(1)|浏览(145)

有没有更快的方法来过滤zip文件?2我的代码逐行读取文件,所以数据加载非常慢。3我可以一次过滤多行吗?

$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()
sczxawaw

sczxawaw1#

代码的问题并不是因为你是逐行阅读内容的,真正的问题是由于在每次循环迭代时追加到一个文件中。我假设你希望将所有与Order1匹配的行从Zip Entry添加到TestFile.txt中。在这种情况下,您应该考虑将StreamWriterStreamReader结合使用。这将在遍历每一行时保持文件流打开。

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
}

相关问题