重命名文件以包含父级和Grantparent 文件夹 - powershell [英] Rename Files to include Parent & Grantparent folder - powershell
问题描述
我的文件夹遵循这样的模式:
I have folders that follow the pattern like this:
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 等,如果可能,将此文件移动到根目录文件夹级别.
I would like to rename the pdfs to something like root folder-grandparent folder-parent folder.1.pdf and root folder-grandparent folder-parent folder.2.pdf etc. and if possible move this file up to the root folder level.
我发现这个 powershell 脚本做了类似的事情,但它只需要父文件夹名称.
I found this powershell script that does something similar but it only takes the parent folder name.
这就是我所拥有的:
#######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
推荐答案
从下面@Joye 的代码中得到了启发.我测试了 Joye 的代码,它只是给了我不支持给定格式"的错误.不确定这是否是我的实验室(Powershell V3).然后我对它进行了一些修改,它在我的实验室中有效:
Got light from @Joye 's code below. I tested Joye's code it just gave me "given format not supported" error. Not sure this is my lab or not (Powershell V3). Then I modified it a little it works in my lab:
get-childitem C:\root folder\grandparent folder\parent folder\*.pdf |
% {
$ParentOjbect =$_.Directory
$Parent =$ParentOjbect.Name
$GrandParent = $ParentOjbect.Parent
Move-item $_ -Destination (Join-Path C:\root folder ('{0}{1}{2}' -f $GrandParent,$Parent,$_.Name))
}
这篇关于重命名文件以包含父级和Grantparent 文件夹 - powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!