這不是很複雜。使用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