【问题标题】:Rename folders based off of newest pdf in folder根据文件夹中最新的 pdf 重命名文件夹
【发布时间】:2019-07-19 01:49:19
【问题描述】:

我目前有 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
     }

【问题讨论】:

  • 使用Get-ChildItem 获取您的文件列表,使用Sort-Object 按日期排序,使用Group-Object 对目录名称进行分组,然后抓取最后一项以找到所需的PDF。最后,使用Rename-Item根据最新的PDF重命名目录。

标签: powershell file pdf directory renaming


【解决方案1】:

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

  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?)
}

【讨论】:

  • 谢谢!你们为我节省了大量时间!像魅力一样工作。由于文件夹中有其他不是 PDF 的文件,我不得不将 Copy-Item *.PDF $Destination 更改为 Copy-Item * $Destination。但我没有澄清,所以这就是我!
  • 有没有办法让它重命名文件夹而不是将所有内容复制到新文件夹中?我只是在我在远程服务器上工作时才问,并且处理需要更多时间而不是简单地重命名。
  • 是的。就像@Lee_Dailey 说的Rename-Item $dir.Name $NewestPDF.BaseName 应该可以工作。然后你可以用 $Destination 取出这三行。从您的原始脚本看来,您想要复制而不是移动。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2014-12-11
  • 1970-01-01
相关资源
最近更新 更多