且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 PowerShell 读取 zip 文件中的 csv 文件的内容

更新时间:2023-12-04 21:19:52

有多种方法可以实现:

1.下面是一个使用 Ionic.zip dll 的示例:

clear
Add-Type -Path "E:\sw\NuGet\Packages\DotNetZip.1.9.7\lib\net20\Ionic.Zip.dll"
$zip = [Ionic.Zip.ZipFile]::Read("E:\E.zip")

$file = $zip | where-object { $_.FileName -eq "XMLSchema1.xsd"}

$stream = new-object IO.MemoryStream
$file.Extract($stream)
$stream.Position = 0

$reader = New-Object IO.StreamReader($stream)
$text = $reader.ReadToEnd()
$text

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

它按名称选择文件 (XMLSchema1.xsd) 并将其提取到内存流中.然后,您需要将内存流读入您喜欢的内容(在我的示例中为字符串).

It's picking the file by name (XMLSchema1.xsd) and extracting it into the memory stream. You then need to read the memory stream into something that you like (string in my example).

2.在 Powershell 5 中,您可以使用 Expand-Archive,请参阅:https://technet.microsoft.com/en-us/library/dn841359.aspx?f=255&MSPPError=-2147217396

它会将整个存档提取到一个文件夹中:

It would extract entire archive into a folder:

Expand-Archive "E:\E.zip" "e:\t"

请记住,提取整个存档需要时间,然后您必须清理临时文件

Keep in mind that extracting entire archive is taking time and you will then have to cleanup the temporary files

3.还有一种仅提取 1 个文件的方法:

$shell = new-object -com shell.application
$zip = $shell.NameSpace("E:\E.zip")
$file =  $zip.items() | Where-Object { $_.Name -eq "XMLSchema1.xsd"}
$shell.Namespace("E:\t").copyhere($file)

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