Welcome Forums General PowerShell Q&A How to delete a subdirectory (not directory) from a zip file

Viewing 2 reply threads
  • Author
    • #68281
      Topics: 1
      Replies: 1
      Points: 0
      Rank: Member

      Gentleman, I am new to PowerShell. I am struggling writing a script to delete certain sub-directories from a zipfile. I will appreciate your help.
      This is my code:
      $currentDate = get-date -uformat “%Y%m%d” # For the example, the folder exists, it is a given.
      $outputFolder = “C:\backups\CRMS\CRMS_” + $currentDate
      #Delete Logs folders from each zip file
      $source = $outputFolder + “\*”
      $zipfile = $outputFolder + “\oneOfmanyZipFiles.zip”
      $files = “mapi” #this is the name of the subdirectory that I should remove from the zip file
      $stream = New-Object IO.FileStream($zipfile, [IO.FileMode]::Open)
      $mode = [IO.Compression.ZipArchiveMode]::Update
      $zip = New-Object IO.Compression.ZipArchive($stream, $mode)
      #Here i need to tell PS that the subdirectory is inside a directory named “FirstFolderInZip”
      #then, I need to delete the folder named “mapi”
      #I tried this but does not work:
      ($zip.Entries | ? { $files -contains $_.Name }) | % { $_.Delete() }


      Thanks for your support.

    • #68295
      Topics: 18
      Replies: 4872
      Points: 1,902
      Helping HandTeam Member
      Rank: Community Hero

      Well, you’re actually writing .NET code, so posting in someplace like StackOverflow.com might yield more and better answers. But, I don’t think those .NET classes actually support what you’re doing. Have you tried doing this interactively?

      That is, have you tried running these commands one at a time from the console? I’m wondering if $zip.Entries ends up containing what you expect, and what the product of your Where-Object statement is.

    • #68370
      Topics: 1
      Replies: 1
      Points: 0
      Rank: Member

      Don, thanks for replying to my post.
      The code works. I have steeped in one line at the time. The line that does not work is: ($zip.Entries | ? { $files -contains $_.Name }) | % { $_.Delete() } which I copied from the PowerShell forums.

      If I assign $zip.Entries to a variable, the result is a list of the file names, therefore I cannot use it.
      My plan is to use the Delete method of the class ZipArchiveEntry on each of the folders that I need to remove from the zip file. The problem is that I am unable to create an instance of that class. I do not know how to do it. There is an example in MSDN but I am unable to implement it in PowerShell: https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchiveentry(v=vs.110).aspx

      My issue if lack of knowledge with the Powershell language.



Viewing 2 reply threads
  • The topic ‘How to delete a subdirectory (not directory) from a zip file’ is closed to new replies.