我目前有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
$Destination = Join-Path $_.Directory $_.BaseName
将更可靠地获取新文件夹名称,在文件名嵌入了'.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?)
}