使用Powershell在子文件夹中编辑zip文件内容 [英] Edit zip file content in subfolder with Powershell

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

问题描述

我正在尝试更新从Excel文档创建的zip文件的内容。我要替换\zipfile\xl\connections.xml的某些内容。

I'm trying to update the contents of a zip file created from an Excel document. I want to replace some of the content of \zipfile\xl\connections.xml.

此部分脚本将列出zip文件的内容:

This partial script will list the contents of the zip file:

$shell_app = new-object -com shell.application
$zip = "$destination\exceltemplates\Templates\Template1.xlsx.zip"
$zip_file=$shell_app.NameSpace($zip)
$zip_file.Items() | Select Path

但是我尝试的每种更新方法都产生了错误。

But every update method I've tried has generated an error. What's the next step needed to access and update a file in the zip file?

推荐答案

这不是很复杂。下一步,访问和更新zip文件中的文件需要做什么?使用PowerShell v3.0或更高版本(以及标准的.NET System.IO库)更加容易。

This is not very complicated. Using PowerShell v3.0 or higher (and the standard .NET System.IO libraries) is easier.

# Parameters
$zipfileName = "E:\temp\WebsitePackage.zip"
$fileToEdit = "robots.txt"
$contents = "User-agent: *
Disallow: /"

# Open zip and find the particular file (assumes only one inside the Zip file)
Add-Type -assembly  System.IO.Compression.FileSystem
$zip =  [System.IO.Compression.ZipFile]::Open($zipfileName,"Update")
$robotsFile = $zip.Entries.Where({$_.name -eq $fileToEdit})

# Update the contents of the file
$desiredFile = [System.IO.StreamWriter]($robotsFile).Open()
$desiredFile.BaseStream.SetLength(0)
$desiredFile.Write($contents)
$desiredFile.Flush()
$desiredFile.Close()

# Write the changes and close the zip file
$zip.Dispose()
Write-Host "zip file updated"

下一个问题是如何快速检查更改是否成功?简单修改脚本,即可读取Zip文件中的文件内容:

The next problem is how to quickly check that your changes were successful? A simple adaptation of the script allows you to read the contents of file inside a Zip file:

# Parameters
$zipfileName = "E:\temp\WebsitePackage.zip"
$fileToRead = "robots.txt"

# Open zip and find the particular file (assumes only one inside the Zip file)
Add-Type -assembly  System.IO.Compression.FileSystem
$zip =  [System.IO.Compression.ZipFile]::Open($zipfileName,"Update")
$robotsFile = $zip.Entries.Where({$_.name -eq $fileToRead})

# Read the contents of the file
$desiredFile = [System.IO.StreamReader]($robotsFile).Open()
$text = $desiredFile.ReadToEnd()

# Output the contents
$text

$desiredFile.Close()
$desiredFile.Dispose()

# Close the zip file
$zip.Dispose()

本文提供了有用的背景材料: https://mcpmag.c om / articles / 2014/09/29 / file-frontier-part-6.aspx

There is useful background material at this article: https://mcpmag.com/articles/2014/09/29/file-frontier-part-6.aspx

这篇关于使用Powershell在子文件夹中编辑zip文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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