根据文件夹中的最新pdf重命名文件夹

问题描述 投票:0回答:1

我目前有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
     }
powershell file pdf directory renaming
1个回答
0
投票

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

  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?)
}
© www.soinside.com 2019 - 2024. All rights reserved.