powershell - 在 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
解决方案
我遇到了同样的问题,看起来他们摆脱了在 .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)
}
推荐阅读
- android - 已创建时未找到通知通道
- syntax - 在 Codesys 的数组中制作子数组?
- swift - 当单击文本字段进行编辑时,UIScrollView 中的 UITextField 会冻结应用程序
- c# - Visual Studio Pro s2017 中的包管理器控制台 Enable-Migrations CommandNotFoundException
- flyway - 是否可以通过命令行使用 Flyway 在日志中显示插入/更新次数的结果?
- google-apps-script - 将所有根文件夹文件移动到文件夹中而不创建副本
- angular - 角度条件验证
- python - 如何在熊猫数据框中跨轴 1 相乘?
- react-native - Expo:选择平面列表的多个项目(更改样式)
- python - 寻找位置向量的零点