我有遵循以下模式的文件夹:
C:\root folder\grandparent folder\parent folder\00001.pdf
C:\root folder\grandparent folder\parent folder\00002.pdf
我想将 pdf 重命名为 root folder-grandparent folder-parent folder.1.pdf 和 root folder-grandparent folder-parent folder.2.pdf 等,如果可能的话,将这个文件移动到根文件夹级别。
我发现这个 powershell 脚本做了类似的事情,但它只需要父文件夹名称。
这就是我所拥有的:
#######Rename script#############
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
Function renameFiles
{
# Loop through all directories
$dirs = dir $path -Recurse | Where { $_.psIsContainer -eq $true }
Foreach ($dir In $dirs)
{
# Set default value for addition to file name
$i = 1
$newdir = $dir.name + "_"
# Search for the files set in the filter (*.pdf in this case)
$files = Get-ChildItem -Path $dir.fullname -Filter *.pdf -Recurse
Foreach ($file In $files)
{
# Check if a file exists
If ($file)
{
# Split the name and rename it to the parent folder
$split = $file.name.split(".pdf")
$replace = $split[0] -Replace $split[0],($newdir + $i + ".pdf")
# Trim spaces and rename the file
$image_string = $file.fullname.ToString().Trim()
"$split[0] renamed to $replace"
Rename-Item "$image_string" "$replace"
$i++
}
}
}
}
# RUN SCRIPT
renameFiles