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

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

问题描述

我有一个zip文件,其中包含几个CSV文件。如何读取这些CSV文件的内容,而无需使用PowerShell提取zip文件?

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?

我一直在使用读归档 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参数过滤。 strong>

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

推荐答案

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

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

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

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