首页 > 解决方案 > 根据文件夹中最新的 pdf 重命名文件夹

问题描述

我目前有 20000 多个文件夹,这些文件夹在创建时会给出随机字符串。我想用每个文件夹中修改的最后一个 PDF 的名称重命名每个文件夹。我肯定在我的头上。当前脚本似乎只是移动 PDF 和/或文件夹,而不重命名它或使用 PDF 名称创建文件夹。

Get-ChildItem -Path $SourceFolder -Filter *.pdf |
 ForEach-Object {
     $ChildPath = Join-Path -Path $_.Name.Replace('.pdf','') -ChildPath $_.Name

     [System.IO.FileInfo]$Destination = Join-Path -Path $TargetFolder -ChildPath $ChildPat

     if( -not ( Test-Path -Path $Destination.Directory.FullName ) ){
         New-Item -ItemType Directory -Path $Destination.Directory.FullName
         }

     Copy-Item -Path $_.FullName -Destination $Destination.FullName
     }

标签: powershellfilepdfdirectoryrenaming

解决方案


欢迎您,罗伯特!您的脚本发生了一些事情:

  1. 有一个错字:$ChildPat
  2. 您不需要 FileInfo 对象来创建新目录,也不能从不存在的路径创建一个。$Destination = Join-Path $_.Directory $_.BaseName在文件名嵌入“.pdf”的特殊情况下,将更可靠地获取新文件夹名称
  3. 它没有获取最新的 PDF。

假设您只想获取具有 PDF 的文件夹,您应该为每个文件夹有一个嵌套的 Get-ChildItem,正如@Lee_Dailey 建议的那样:

Push-Location $SourceFolder
Foreach ($dir in (Get-ChildItem *.pdf -Recurse | Group-Object Directory | Select Name )){
        Push-Location $dir.Name
        $NewestPDF = Get-ChildItem *.pdf | Sort-Object ModifiedDate | Select -Last 1
        $Destination = Join-Path $dir.Name "..\$($NewestPDF.BaseName)"
        If(!(Test-Path $Destination)){New-Item $Destination -ItemType Directory}
        Copy-Item *.PDF $Destination 
        Pop-Location
        #Remove-Item $dir.Name #uncomment to remove the old folder (is it empty?)
}

推荐阅读