Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell add file to zip

Tags:

powershell

zip

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

like image 255
mjsolo Avatar asked Dec 05 '12 17:12

mjsolo


People also ask

How do I zip a file in PowerShell?

Compress-Archive uses the Path parameter to specify the root directory, C:\Reference with an asterisk ( * ) wildcard. The DestinationPath parameter specifies the location for the archive file. The Draft. zip archive contains the root directory's files and subdirectories.

How do you append to a file in PowerShell?

In PowerShell, the Add-Content cmdlet is used to append data in a file. The content which needs to be appended is specified in this command. Here, -Path tells the exact location of the file, and the -Value is the text which will be appended in it.


1 Answers

To create a zip archive:

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

like image 77
Zimba Avatar answered Oct 02 '22 16:10

Zimba