【问题标题】:powershell add file to zippowershell 将文件添加到 zip
【发布时间】:2012-12-05 17:32:19
【问题描述】:

我正在尝试使用 powershell 将文件添加到 zip 文件中

我可以创建 zip 文件,但不知道如何将我的文件添加到其中

我正在使用

$zipfilename = 'c:\cwRsync\backup.zip'
$file = 'c:\cwRsync\backup.log'
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
$zipfile = (New-Object -ComObject shell.application).NameSpace($zipfilename)
$zipfile.MoveHere($file.FullName)

这会创建 zip 文件,但不会添加新文件

我尝试了在 stackoverflow 上找到的以下代码

$zipfilename = "a.zip"
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
$app = new-object -com shell.application
$zip = ( get-item a.zip ).fullname
$folder = $app.namespace( $zip )
$item = new-item file.txt -itemtype file -value "Mooo" -force
$folder.copyhere( $item.fullname )

但是添加了一个由 powershell 创建的文件,而我想添加一个现有的文件

任何帮助将不胜感激

【问题讨论】:

  • 通过将 $zipfile.MoveHere($file.FullName) 更改为 $zipfile.MoveHere($file) 并在脚本末尾添加 sleep 1 使其工作,问题似乎是由当我从命令行调用脚本时

标签: powershell zip


【解决方案1】:

创建 zip 存档:

powershell Compress-Archive %file% %file%.zip

要替换存档(使用不同的文件):

powershell Compress-Archive -force %different_file% %file%.zip

将文件添加到(现有)存档:

powershell Compress-Archive -update %2nd_file% %file%.zip

在 Win 10 CMD Powershell 5.1 上测试

【讨论】:

  • 这是 IMO 的正确答案,非常感谢,你帮了我很大的忙 :) 我们只是缺乏一种明确的方法来从现有存档中删除文件以使其完美。
  • 不客气。 Compress-Archive cmdlet 使用 Microsoft .NET API System.IO.Compression.ZipArchive 来压缩文件,因此文件仍然可以通过 powershell 为 removed from archives
【解决方案2】:

CopyHere 函数只接受一个字符串,它是您文件的路径。例如:

$folder.copyhere( "c:\PathToYourFile\YourFile" )

编辑:以下提示中提到的 Powershell 包不再可用。我把它留在这里,以防有人发现它存档在某个地方,并可以用链接更新这篇文章。

提示:

Powershell Pack Module 有一些有用的工具,其中之一是一个 zip 实用程序,它可以将您的代码减少到 1 行:

Copy-ToZip "c:\PathToYourFile\YourFile" -ZipFile a.zip

【讨论】:

  • 谢谢,我去看看 Powershell Pack 模块
  • 我仍然想让我的脚本工作 - 如果我使用 $zipfile.MoveHere($file) 它仍然不起作用
  • 尝试了 copy-tozip,它有点工作,但有大 zip 文件的问题,现在使用批处理文件中的 7zip - 像梦一样工作
  • PowerShellPack 的链接返回:“存档库已停用”。
【解决方案3】:

我从我的笔记中提取了这个。从脚本专家的网站上得到它,也许这会有所帮助......

$source = "D:\temp\test"
$destination = "d:\temp\csvdir_Backup.zip"
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($Source, $destination) 

【讨论】:

  • 欢迎来到 Stack Overflow!这看起来像是一个 try-this-and-let-me-know-how-it-goes 响应,属于评论而不是答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多