PowerShell CompressArchive -更新到zip文件内的目录



我正在尝试编写一个PowerShell脚本来更新zip文件中的文件,因为我需要自动执行许多zip文件。我的问题是,我需要更新的文件位于zip中的几个目录中,例如:

myZip.zip→dir1/dir2 file.txt

我正在尝试使用诸如

之类的命令
Compress-Archive -Path .file.txt -Update -DestinationPath .myZip.zip

但是当我运行它时,文件被添加到zip文件的根目录中,而不是像我需要的那样添加到dir1/dir2/目录中。

这可能吗?

计算出-Path必须引用与zip文件中相同的目录结构

我的测试zip具有以下目录结构:

myZip.zip
-> dir1
-> -> dir2
-> -> -> dir3
-> -> -> -> myFile.txt

我的参考目录被定义为:

dir1
-> dir2
-> -> dir3
-> -> -> myFile.txt

我可以运行

Compress-Archive -Path .dir1 -DestinationPath .myZip.zip -Update

这将把文件放入正确的目录。

感谢@SantiagoSquarzon在这里,@metablaster在相关的票

这就是如何使用。net api直接更新ZipArchiveEntry,这种方法不需要外部应用程序或Compress-Archive。它也不需要模拟Zip结构来瞄准正确的文件,相反,它需要您通过传递正确的相对路径(dir1/dir2/dir3/myFile.txt)来瞄准正确的Zip条目。)作为.GetEntry(..)的参数。

using namespace System.IO
using namespace System.IO.Compression
Add-Type -AssemblyName System.IO.Compression
$filestream = (Get-Item .myZip.zip).Open([FileMode]::Open)
$ziparchive = [ZipArchive]::new($filestream, [ZipArchiveMode]::Update)
# relative path of the ZipEntry must be precise here
# ZipEntry path is relative, note the forward slashes are important
$zipentry   = $ziparchive.GetEntry('dir1/dir2/dir3/myFile.txt')
$wrappedstream = $zipentry.Open()
# this is the source file, used to replace the ZipEntry
$copyStream    = (Get-Item .file.txt).OpenRead()
$copyStream.CopyTo($wrappedstream)
$wrappedstream, $copyStream, $ziparchive, $filestream | ForEach-Object Dispose

最新更新