且构网

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

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

更新时间:2023-12-04 21:28:40

有多种方法可以实现这一目标:

There are multiple ways of achieving this:

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 a>

它会将整个归档文件解压缩到一个文件夹中:

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。还有一种方法只提取一个文件:

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