powershell add file to zip

2020-04-10 00:56发布

I'm trying to add a file to a zip file using powershell

I can create the zip file but can't work out how to add my file to it

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

I tried the following code I found on stackoverflow which works

$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

Any help would be much appreciated

2条回答
Anthone
2楼-- · 2020-04-10 01:43

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) 
查看更多
ゆ 、 Hurt°
3楼-- · 2020-04-10 01:57

The CopyHere function just takes a string that is the path to your file. 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:

Copy-ToZip "c:\PathToYourFile\YourFile" -ZipFile a.zip
查看更多
登录 后发表回答