这不是很复杂。使用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
我从来没有到ZIP操纵与PS,但是你能分享你收到的错误吗?这会让问题更加完整 – Koliat 2014-08-28 08:56:22
当我添加如下内容时: – 2014-08-28 13:48:28
当我添加如下内容:foreach($ item in $ zip.items()) { \t(Get-Content $ connstring)| Foreach-Object {$ _ -replace“\ {DatabaseServer \}”,$ sqlDatabase} | Set-Content $ connstring }我得到“你不能调用一个空值表达式的方法”错误。我想编辑压缩文件中子文件夹中的文件。 – 2014-08-28 13:54:46