问题描述
我有一个简单的脚本,用于解压缩文件并写入目录。如果目标目录中已存在该文件,则无法获取脚本来覆盖文件。您能帮我确定我所缺少的吗?
# 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
解决方法
我遇到了同样的问题,看来他们摆脱了覆盖.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)
}