我正在尝试更新从 Excel 文档创建的 zip 文件的内容。我想替换\zipfile\xl\connections.xml 的一些内容。
该部分脚本将列出 zip 文件的内容:
$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
但我尝试过的每种更新方法都会产生错误。访问和更新 zip 文件中的文件下一步需要做什么?
这并不是很复杂。使用 PowerShell v3.0 或更高版本(以及标准 .NET System.IO 库)更容易。
# 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 文件内的文件内容:
# 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.com/articles/2014/09/29/file-frontier-part-6.aspx https://mcpmag.com/articles/2014/09/29/file-frontier-part-6.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)