我有下面的PowerShell脚本,将在其子文件夹中找到的所有.jpg文件放到'Scans'文件夹中,并重命名这些.jpg文件以匹配其各自父目录(=子文件夹)的名称。当存在多个.jpg文件时,重命名过程会自动将一个数字添加到文件名,如File_1,jpg和File_2.jpg。如何在分割和重命名时忽略文件名中的括号?
所以脚本运行一个文件夹可能看起来像在此之前:
Parent Directory from which script is executed | Subfolder (containing .jpg files and the 'Scans' subfolder) | Scans (=folder) Photo.jpg Picture.jpg Shot(1).jpg Shot(2).jpg
一旦脚本运行的文件夹看起来是这样的:
Parent Directory from which script is executed | Subfolder (containing the 'Scans' subfolder) | Scans (=folder containing supposed to contain all .jpg files) | Subfolder_1.jpg Subfolder_2.jpg Shot(1) (=file moved but extension stripped) Shot(2) (=file not moved and extension stripped)
所以包含括号'的.jpg文件Shot(1).jpg'和'Shot(2).jpg'没有正确重命名并移动到'Scans'文件夹。实际上他们的'.jpg'扩展名被剥离了。
脚本只要.jpg文件不包含任何括号(()
)工作正常,如
- 的投篮(1).JPG“和 '射击(2).JPG' →当存在多个.jpg文件时
- 'Pics(2001).jpg'→当子文件夹名称包含像'Pics(2001)'中的括号时,.jpg被正确地重命名,但随后包含括号并且脚本将再次失败当第二次运行时。
我已阅读有关转义其他线程中的特殊字符,但一直未能在下面的脚本中实现解决方案。有没有人有解决方案,以便在移动和重命名这些.jpg文件时,括号不会引起任何问题?
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
function renamePhotos {
# Loop through all directories
$dirs = dir $path -Recurse | Where { $_.psIsContainer -eq $true }
foreach ($dir In $dirs) {
$i = 1
$newdir = $dir.parent.name + "_"
$images = Get-ChildItem -Path $dir.fullname -Filter *.jpg -Recurse
foreach ($image In $images) {
$split = $image.name.split(".jpg")
$replace = $split[0] -Replace $split[0],($newdir + $i + ".jpg")
$image_string = $image.fullname.ToString().Trim()
Rename-Item "$image_string" "$replace"
$i++
Move-Item -Path $dir\*.jpg -Destination $dir\Scans
}
}
}
# RUN SCRIPT
renamePhotos
"SCRIPT FINISHED"
为什么不改变行:' move-item -path $ dir \ *。jpg -destination $ dir \ Scans \ *。jpg',因为我认为这将涵盖您需要的内容? – Leptonator