[英]powershell add file to zip
I'm trying to add a file to a zip file using powershell我正在尝试使用 powershell 将文件添加到 zip 文件
I can create the zip file but can't work out how to add my file to it我可以创建 zip 文件,但不知道如何向其中添加我的文件
I'm using我正在使用
$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)
This create the zip file but doesn't add the new file这会创建 zip 文件但不会添加新文件
I tried the following code I found on stackoverflow which works我尝试了以下在 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 )
but that add a file created by powershell whereas I want to add an existing file但是添加了一个由 powershell 创建的文件,而我想添加一个现有文件
Any help would be much appreciated任何帮助将非常感激
To create a zip archive:要创建 zip 存档:
powershell Compress-Archive %file% %file%.zip
To replace the archive (with a different file):要替换存档(使用不同的文件):
powershell Compress-Archive -force %different_file% %file%.zip
To add a file to the (existing) archive:将文件添加到(现有)存档:
powershell Compress-Archive -update %2nd_file% %file%.zip
Tested on Win 10 CMD Powershell 5.1在 Win 10 上测试 CMD Powershell 5.1
The CopyHere
function just takes a string that is the path to your file. CopyHere
函数仅采用字符串作为文件路径。 For example: 例如:
$folder.copyhere( "c:\PathToYourFile\YourFile" )
Tip: 小费:
The Powershell Pack Module has some useful tools, one of which is a zip utility, which will reduce your code to 1 line: Powershell Pack模块具有一些有用的工具,其中一个是zip实用程序,它将把您的代码减少到1行:
Copy-ToZip "c:\PathToYourFile\YourFile" -ZipFile a.zip
I pulled this from my notes. 我从笔记中拉了这个。 Got it off the scripting guy's website, maybe this will help... 从脚本专家的网站上删除它,也许这会有所帮助...
$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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.