PowerShell递归搜索db_execute下json/txt文件夹并打包Zip的问题排查
问题排查
原脚本存在以下核心问题:
- 初始打包错误:第一行
Compress-Archive -LiteralPath $currentDir ...直接把当前目录所有内容打包进zip,这是多余内容的主要来源,创建空zip完全不需要这种操作。 - Filter参数误用:
$folderNames里的db_execute\json是路径格式,但Get-ChildItem的-Filter仅能匹配目录/文件的名称,无法识别带路径的筛选条件,导致无法正确定位db_execute下的json和txt子目录。 - 路径结构失控:就算找到目标目录,直接用
Compress-Archive添加时,会保留该目录在当前目录下的完整嵌套路径(比如subfolder\db_execute\json),无法实现只保留db_execute→json/txt的预期结构。
修正方案
以下脚本通过临时目录统一整理结构,确保zip内的层级完全符合要求:
$zipFileName = "Folders.zip" $currentDir = Get-Location $tempDir = Join-Path -Path $env:TEMP -Path "DbExecuteTemp_$(Get-Random)" # 清理旧文件与临时目录 if (Test-Path $zipFileName) { Remove-Item $zipFileName -Force } if (Test-Path $tempDir) { Remove-Item $tempDir -Recurse -Force } # 创建临时目录下的目标结构 $targetDbDir = Join-Path -Path $tempDir -Path "db_execute" New-Item -Path $targetDbDir -ItemType Directory | Out-Null New-Item -Path (Join-Path $targetDbDir "json") -ItemType Directory | Out-Null New-Item -Path (Join-Path $targetDbDir "txt") -ItemType Directory | Out-Null # 递归查找所有db_execute目录 $dbExecuteDirs = Get-ChildItem -Path $currentDir -Directory -Recurse -Filter "db_execute" foreach ($dbDir in $dbExecuteDirs) { # 复制json目录内容到临时结构 $jsonSrc = Join-Path -Path $dbDir.FullName -Path "json" if (Test-Path $jsonSrc) { Copy-Item -Path "$jsonSrc\*" -Destination (Join-Path $targetDbDir "json") -Recurse -Force } # 复制txt目录内容到临时结构 $txtSrc = Join-Path -Path $dbDir.FullName -Path "txt" if (Test-Path $txtSrc) { Copy-Item -Path "$txtSrc\*" -Destination (Join-Path $targetDbDir "txt") -Recurse -Force } } # 打包目标结构 Compress-Archive -Path (Join-Path $tempDir "db_execute") -DestinationPath $zipFileName -CompressionLevel Optimal # 清理临时目录 Remove-Item $tempDir -Recurse -Force
脚本说明
- 临时目录隔离:用系统临时目录创建随机命名的临时文件夹,避免修改原目录结构。
- 结构预定义:在临时目录下预先创建
db_execute\json和db_execute\txt的层级,确保最终zip内的结构完全符合预期。 - 内容合并:递归找到所有
db_execute目录,将其中json和txt子目录的内容合并到临时目录的对应位置(多份同名内容会自动覆盖,可根据需求调整)。 - 自动清理:打包完成后自动删除临时目录,避免残留文件。
内容的提问来源于stack exchange,提问作者Ashar
相关产品推荐
相关产品推荐

