6

I am trying to copy/move one text file to the zip. I don't want to unzip it, copy the file and zip it back. Is there any way we can directly copy or move text file to the zip in powershell. When i am doing it in powershell, it's doing after that when i try to look inside the zip it's saying invalid path.

Powershell commands:

$A = "20160914.4"

New-Item "C:\test\VersionLabel.txt" -ItemType file

$A | Set-Content "C:\test\VersionLabel.txt"

Copy-Item "C:\test\VersionLabel.txt" "C:\test\Abc.zip"  -Force

Error: The compressed folder is invalid

sodawillow
  • 12,497
  • 4
  • 34
  • 44
Meet101
  • 711
  • 4
  • 18
  • 35
  • [How to create a zip archive with PowerShell?](https://stackoverflow.com/a/12978117) you can do it manually via ZipArchive or ZipPackage or zip folder namespace. The linked question has many answers. – wOxxOm Sep 14 '16 at 20:15

2 Answers2

14

>= PowerShell 5.0

Per @SonnyPuijk's answer above, use Compress-Archive.

clear-host
[string]$zipFN = 'c:\temp\myZipFile.zip'
[string]$fileToZip = 'c:\temp\myTestFile.dat'
Compress-Archive -Path $fileToZip -Update -DestinationPath $zipFN

< PowerShell 5.0

To add a single file to an existing zip:

clear-host
Add-Type -assembly 'System.IO.Compression'
Add-Type -assembly 'System.IO.Compression.FileSystem'

[string]$zipFN = 'c:\temp\myZipFile.zip'
[string]$fileToZip = 'c:\temp\myTestFile.dat'
[System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN, ([System.IO.Compression.ZipArchiveMode]::Update))
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf))
$ZipFile.Dispose()

To create a single file zip file from scratch:

Same as above, only replace: [System.IO.Compression.ZipArchiveMode]::Update

With: [System.IO.Compression.ZipArchiveMode]::Create

Related Documentation:

JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
  • NB: To create a zip file from a directory, see http://stackoverflow.com/a/20070550/361842 – JohnLBevan Dec 13 '16 at 15:45
  • ps. Some good notes on various zip pieces here: https://www.codeproject.com/Articles/381661/Creating-Zip-Files-Easily-in-NET-4-5 – JohnLBevan May 03 '19 at 10:17
1

You can use Compress-Archive for this. Copy-Item doesn't support zip files.

If you don't have PowerShell v5 you can use either 7Zip command line or .Net

Matt
  • 45,022
  • 8
  • 78
  • 119
Sonny Puijk
  • 114
  • 4
  • is there any other way to do this. i don't want to use 72ip – Meet101 Sep 14 '16 at 19:10
  • Only other method I know is using the dotnet library. Scripting guy already wrote a blog about this. https://blogs.technet.microsoft.com/heyscriptingguy/2015/03/09/use-powershell-to-create-zip-archive-of-folder/ – Sonny Puijk Sep 14 '16 at 20:15