powershell - 根据文件夹中最新的 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
}
解决方案
欢迎您,罗伯特!您的脚本发生了一些事情:
- 有一个错字:
$ChildPat
- 您不需要 FileInfo 对象来创建新目录,也不能从不存在的路径创建一个。
$Destination = Join-Path $_.Directory $_.BaseName
在文件名嵌入“.pdf”的特殊情况下,将更可靠地获取新文件夹名称 - 它没有获取最新的 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?)
}
推荐阅读
- vue.js - Vuex store 不能在 axios 处理程序中使用
- google-drive-api - 如何在不需要用户登录的情况下上传到 google drive api?
- nginx - Cloudflare 和 Nginx 代理管理器出现问题,无法连接到我的本地服务器。(错误 522/523)
- java - 运算符 ^ 未定义参数类型 long, boolean
- pandas - 我将如何访问这个 pandas dataFrame 的各个元素?
- php - 密码验证不断返回错误的登录凭据php
- python - 如何将数字按 5 分组?
- php - 将上传的图片从 Mysql 渲染到前端
- macos - 无法使用新的 Mac M1 构建 Docker 映像
- angular - Angular:通过http请求进行网络查询,但得到CORS错误