Elroy Taulton
Elroy Taulton

Reputation: 5

Overwrite same names from zip file in Powershell

I have a simple script that is unzipping files and writing to a directory. I have been unable to get the script to overwrite files if the file already existed in the destination directory. Can you help me identify what I am missing.

# System Variables
#--------------------------------
$src  = "C:\Work\ZipFileSource\"
$dest = "C:\Work\ZipResult\"
$finish = "C:\Work\ZipFinish\"
#--------------------------------
Function UnZipAll ($src, $dest)
 {
    [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
#Add-Type -AssemblyName System.IO.Compression.FileSystem
$zps = Get-ChildItem $src -Filter *.zip
foreach ($zp in $zps)
    {
        $all = $src + $zp
        [System.IO.Compression.ZipFile]::ExtractToDirectory($all, $dest, $true)
    }
}
UnZipAll -src $src -dest $dest
Move-Item -path $src"*.zip" $finish

Upvotes: 0

Views: 886

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36297

I ran into that same issue, it looks like they got rid of the option to overwrite files in .Net 4, so I use a work around. I opened the Zip file in read only, got the list of files from it, figured out the destination for each file (joined the partial file path from the zip file, and the destination root), and deleted any files found that would have to be overwritten. Then I extracted the zip file without incident.

To apply that to your current loop you'd do something like:

foreach ($zp in $zps)
    {
    # Open the zip file to read info about it (specifically the file list)
    $ZipFile = [io.compression.zipfile]::OpenRead($zp.FullName)
    # Create a list of destination files (excluding folders with the Where statement), by joining the destination path with each file's partial path
    $FileList = $ZipFile.Entries.FullName|Where{$_ -notlike '*/'}|%{join-path $dest ($_ -replace '\/','\')}
    # Get rid of our lock on the zip file
    $ZipFile.Dispose()
    # Check if any files already exist, and delete them if they do
    Get-ChildItem -Path $FileList -Force -ErrorAction Ignore|Remove-Item $_ -Force -Recurse
    # Extract the archive
    [System.IO.Compression.ZipFile]::ExtractToDirectory($zp.FullName,$dest)
    }

Upvotes: 2

Related Questions