filepowershellreplacephp-ziparchive

Replacing files in a *.zip file without unzipping (extracting) in Powershell


Hi everyone!

Currently, I am trying to create a script in Powershell that will replace/delete files in a *.zip file without extracting it.

I know it is possible to do manually by using applications like 7Zip and WinRAR or by simply opening a zip archive in Folder Explorer, but I am looking for a way to automate this action.

I am new to powershell and to programming in general, so I cannot come up with any preliminary code. I tried to search for answers on the net, but failed to find anything that would work for me.

So the question is:
Lets say we have a zip archive called Photos (Photos.zip). The archive contains 5 images. How do I replace/delete images in Photos.zip without extracting it in Powershell?

Any code/ideas/links to helpful resources would be highly appreciated.


Solution

  • I used the following solution.

    First I moved old files from the archive to a temporary folder by using this code:

    #Path to the temporary folder
    $pathToTemporaryFolder = "C:\...\Temporary"
    #Path to a file that will be moved from the archive to the temporary folder
    $pathToFileToBeMoved = "C:\...\Photos.zip\My Photos\My Image.png"
    (New-Object -COM Shell.Application).NameSpace("$pathToTemporaryFolder").MoveHere("$pathToFileToBeMoved")
    

    Then, I copied some new files to the archive:

    #Path to the folder with a new file
    $pathToFolderWithNewFile = "C:\...\New Images\My New Image.jpeg"
    #Path to a folder in the archive where the new file will be copied to
    $pathToFolderInArchive = "C:\...\Photos.zip\My Photos"
    (New-Object -COM Shell.Application).NameSpace("$pathToFolderInArchive").CopyHere("$pathToFolderWithNewFile")
    

    Finally I deleted the temporary folder

    Remove-Item -Path "C:\...\Temporary" -Recurse
    

    This is how I deleted files from the archive and copied new files to it without unzipping/extracting.