使用powershell用pdftk合并多个子文件夹中的PDF,然后删除原始PDF文件

Using powershell to merge PDFs in multiple subfolders with pdftk and then delete original PDF files

我有一个包含许多子文件夹的根文件夹,每个子文件夹都有多个 PDF。 然后我有一个 powershell 脚本,它遍历文件夹结构并为每个子文件夹创建一个合并的 PDF 文件(使用 PDFtk),如下所示:

    $pdftk = "C:\Program Files (x86)\PDFtk\bin\pdftk.exe"
    $RootFolder = "path to root folder"
    Get-ChildItem -r -include *.pdf | group DirectoryName | % {& $PDFtk $_.group CAT OUTPUT "$($_.Name | Split-Path -Parent)$($_.Name | Split-Path -Leaf)_merged.pdf"}

脚本按要求工作,但是我将处理大量数据,因此我需要在合并完成后从每个文件夹中删除原始 PDF。

基本上,我需要脚本在第一个文件夹 4830_2017 中查找,创建合并文件 4830_2017_merged.pdf,然后删除位于 4830_2017 文件夹中的 PDF,然后再继续下一个文件夹,并做同样的事情。

我正在努力寻找合并后删除每个文件夹内容的正确方法。

感谢您的帮助。

在你的 ForEach-Object script block, $_.Group contains each group's, i.e. each directory's System.IO.FileInfo instances representing the *.pdf files, so you can pipe them to Remove-Item 成功合并后:

(Get-ChildItem -Recurse -Filter *.pdf) | 
  Group-Object DirectoryName | 
    ForEach-Object {
      & $PDFtk $_.Group.FullName CAT OUTPUT "$($_.Name | Split-Path -Parent)$($_.Name | Split-Path -Leaf)_merged.pdf"
      if (0 -eq $LASTEXITCODE) { # If the merge succeeded.
        $_.Group | Remove-Item   # Delete.
      }
    }

注:

  • Get-ChildItem命令包含在(...)中,以确保在进一步处理之前完整收集其输出,以排除新[=14的副作用=] 文件被创建或旧文件被删除影响递归枚举。

    • -Filter *.pdf 用于代替 -Include *.pdf,在这种情况下它在功能上是等效的,但性能要好得多,因为在源头将过滤委托给文件系统 API - 见 .
  • & $PDFtk $_.Group 已更改为 & $PDFtk $_.Group.FullName 以确保传递 完整 文件路径;请注意,在 PowerShell (Core) 7+ 中不再需要这样做,其中 System.IO.FileInfo and System.IO.DirectoryInfo instances consistently stringify to their full paths - see .

  • Group-Object outputs Microsoft.PowerShell.Commands.GroupInfo 个实例。