Windows PowerShell归档脚本异常:含同名文件的打包任务无法完成
解决PowerShell打包脚本无限递归问题
问题根源
脚本陷入无限递归的核心原因是归档过程中生成的temp.zip被纳入了后续的文件搜索范围,导致脚本反复将自身打包进zip文件,无法终止。
修复方案与修正脚本
下面是修正后的脚本,关键修改点包括:
- 明确排除临时归档文件和最终归档文件,避免被搜索捕获
- 拆分逻辑分别处理
deployfiles目录与其他路径的文件,满足“非deployfiles文件仅保留一份,deployfiles下同名文件全包含”的要求
$workspace = "你的工作路径" $itemsToInclude = "file1.txt,file2.dll" # 替换为实际要包含的文件列表 $tempZip = Join-Path $workspace "temp.zip" $finalZip = Join-Path $workspace "yello.zip" # 将逗号分隔的目标文件转为数组 $targetFiles = $itemsToInclude -split ',' | ForEach-Object { $_.Trim() } # 1. 收集非deployfiles目录下的目标文件,每个文件仅保留第一个匹配项 $nonDeployFiles = @() foreach ($file in $targetFiles) { $match = Get-ChildItem -Path $workspace -Filter $file -Recurse -File | Where-Object { $_.DirectoryName -notmatch [regex]::Escape((Join-Path $workspace "deployfiles")) -and $_.FullName -ne $tempZip -and $_.FullName -ne $finalZip } | Select-Object -First 1 if ($match) { $nonDeployFiles += $match } } # 2. 收集deployfiles目录下的所有目标文件 $deployFiles = Get-ChildItem -Path (Join-Path $workspace "deployfiles") -Filter "*" -Recurse -File | Where-Object { $targetFiles -contains $_.Name } # 合并需要归档的文件列表 $filesToArchive = $nonDeployFiles + $deployFiles # 3. 执行归档(先清理旧文件避免冲突) if (Test-Path $tempZip) { Remove-Item $tempZip -Force } Compress-Archive -Path $filesToArchive.FullName -DestinationPath $tempZip -Force # 替换最终归档文件 if (Test-Path $finalZip) { Remove-Item $finalZip -Force } Rename-Item -Path $tempZip -NewName $finalZip
关键细节说明
- 避免递归触发:通过
Where-Object明确排除temp.zip和yello.zip的路径,确保归档文件不会被纳入搜索范围 - 非deployfiles文件去重:用
Select-Object -First 1只保留每个目标文件在非deployfiles路径下的第一个匹配实例 - deployfiles全量收集:单独遍历deployfiles目录,将所有匹配目标文件名的文件全部纳入归档
内容的提问来源于stack exchange,提问作者Ashar
相关产品推荐
相关产品推荐

