首页 > 解决方案 > 在 Powershell 中覆盖 zip 文件中的相同名称

问题描述

我有一个简单的脚本,用于解压缩文件并写入目录。如果文件已存在于目标目录中,我无法让脚本覆盖文件。你能帮我找出我缺少的东西吗?

# 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

标签: powershell

解决方案


我遇到了同样的问题,看起来他们摆脱了在 .Net 4 中覆盖文件的选项,所以我使用了一种解决方法。我以只读方式打开 Zip 文件,从中获取文件列表,找出每个文件的目标(加入 zip 文件的部分文件路径和目标根目录),并删除找到的所有文件被覆盖。然后我毫无意外地提取了 zip 文件。

要将其应用于当前循环,您需要执行以下操作:

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)
    }

推荐阅读