如何用PowerShell递归压缩指定前缀文件并生成对应归档包?
PowerShell 归档脚本实现指定文件分类压缩
以下是满足需求的PowerShell脚本,可实现按前缀筛选文件、自定义归档名称、覆盖已有归档,且支持在多个根目录重复运行:
param( [Parameter(Mandatory=$true)] [string]$RootDirectory ) # 筛选根目录下8位数字命名的日期子目录 $dateDirectories = Get-ChildItem -Path $RootDirectory -Directory | Where-Object { $_.Name -match '^\d{8}$' } foreach ($dir in $dateDirectories) { # 处理L0283前缀的文件 $l0283Files = Get-ChildItem -Path $dir.FullName -File -Filter 'L0283*' if ($l0283Files.Count -gt 0) { # 提取文件名前7位作为归档标识(假设同前缀文件共享该标识) $filePrefix = $l0283Files[0].Name.Substring(0,7) $zipFileName = "400401_${filePrefix}archive.zip" $zipFullPath = Join-Path -Path $dir.FullName -ChildPath $zipFileName # 压缩文件并强制覆盖已存在的归档包 Compress-Archive -Path $l0283Files.FullName -DestinationPath $zipFullPath -Force Write-Host "完成归档: $zipFullPath" } # 处理L0284前缀的文件 $l0284Files = Get-ChildItem -Path $dir.FullName -File -Filter 'L0284*' if ($l0284Files.Count -gt 0) { $filePrefix = $l0284Files[0].Name.Substring(0,7) $zipFileName = "400401_${filePrefix}archive.zip" $zipFullPath = Join-Path -Path $dir.FullName -ChildPath $zipFileName Compress-Archive -Path $l0284Files.FullName -DestinationPath $zipFullPath -Force Write-Host "完成归档: $zipFullPath" } }
使用说明
- 将上述代码保存为
Archive-L028Files.ps1文件。 - 打开PowerShell,切换到脚本所在目录。
- 运行脚本并指定目标根目录:
.\Archive-L028Files.ps1 -RootDirectory "C:\Your\Root\Directory\2022" - 处理其他根目录时,重复执行上述命令并替换对应的
-RootDirectory路径即可。
关键特性
- 自动筛选根目录下8位数字格式的日期子目录,避免处理无关目录。
- 分别处理
L0283*和L0284*前缀的文件,生成对应格式的归档包。 - 使用
-Force参数直接覆盖已存在的同名归档包,无需手动确认。 - 仅当目录下存在对应前缀的文件时才生成归档包,不会创建空压缩文件。
内容的提问来源于stack exchange,提问作者jjthemagicman
相关产品推荐
相关产品推荐

