Delete files from .zip file using Powershell

I am going to write a Powershell script to delete files from a .zip file. In my .zip file I have test.txt (last) test1.txt (older) test2.txt .... testN.txt (oldest), all with different file sizes (or in powershell, it's called Length). I want to leave only 2G or less and delete the rest. It is required to be removed from the oldest. Since the .zip file can be very large. It’s better not to remove it and fasten it again.

Is there any way to achieve this?

Thank you very much.

+2
source share
2 answers

Making this VBScript decision :

$zipfile = 'C:\path\to\your.zip' $files = 'some.file', 'other.file', ... $dst = 'C:\some\folder' $app = New-Object -COM 'Shell.Application' $app.NameSpace($zipfile).Items() | ? { $files -contains $_.Name } | % { $app.Namespace($dst).MoveHere($_) Remove-Item (Join-Path $dst $_.Name) } 

If you have .net Framework 4.5 installed, then something like this should work too:

 [Reflection.Assembly]::LoadWithPartialName('System.IO.Compression') $zipfile = 'C:\path\to\your.zip' $files = 'some.file', 'other.file', ... $stream = New-Object IO.FileStream($zipfile, [IO.FileMode]::Open) $mode = [IO.Compression.ZipArchiveMode]::Update $zip = New-Object IO.Compression.ZipArchive($stream, $mode) ($zip.Entries | ? { $files -contains $_.Name }) | % { $_.Delete() } $zip.Dispose() $stream.Close() $stream.Dispose() 

Brackets around filtering items from the Entries collection are required, because otherwise the subsequent Delete() will modify the collection. This will prevent the reading (and therefore removal) of other items from the collection. The resulting error message is as follows:

  An error occurred while enumerating through a collection: Collection was modified;
 enumeration operation may not execute ..
 At line: 1 char: 1
 + $ zip.Entries |  ?  {$ filesToRemove -contains $ _. Name} |  % {$ _. Delete ()}
 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo: InvalidOperation: (System.Collecti ... ipArchiveEntry]: Enumerator) [], RuntimeException
     + FullyQualifiedErrorId: BadEnumeration 
+6
source

Use 7-Zip , a free Zip tool. The example illustrates how to create a zip archive with 7-Zip in Powershell.

Examine the correct commands to get a list of your zip content and use the d command to delete files from the archive.

+2
source

Source: https://habr.com/ru/post/980935/


All Articles