如何使用 PowerShell 读取 zip 文件中的 csv 文件的内容 [英] How to read contents of a csv file inside zip file using PowerShell

查看:57
本文介绍了如何使用 PowerShell 读取 zip 文件中的 csv 文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 zip 文件,其中包含多个 CSV 文件.如何在不使用 PowerShell 提取 zip 文件的情况下读取这些 CSV 文件的内容?

I have a zip file which contains several CSV files inside it. How do I read the contents of those CSV files without extracting the zip files using PowerShell?

我一直在使用 Read-Archive Cmdlet,它包含在 PowerShell 社区中扩展 (PSCX)

I having been using the Read-Archive Cmdlet which is included as part of the PowerShell Community Extensions (PSCX)

这是我迄今为止尝试过的.

This is what I have tried so far.

$path = "$env:USERPROFILE\Downloads\"
$fullpath = Join-Path $path filename.zip

Read-Archive $fullpath | Foreach-Object {
    Get-Content $_.Name
}

但是当我运行代码时,我收到此错误消息Get-Content : 指定路径 filename.csv 处的对象不存在,或已被 -Include 或 -Exclude 参数过滤.

But when I run the code, I get this error message Get-Content : An object at the specified path filename.csv does not exist, or has been filtered by the -Include or -Exclude parameter.

但是,当我运行 Read-Archive $fullpath 时,它会列出 zip 文件中的所有文件

However, when I run Read-Archive $fullpath, it lists all the file inside the zip file

推荐答案

有多种方法可以实现:

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

这篇关于如何使用 PowerShell 读取 zip 文件中的 csv 文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆