重命名文件以包括Parent& Grantparent文件夹 - powershell

时间:2013-07-24 12:01:53

标签: powershell rename

我的文件夹遵循以下模式:

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等。如果可能的话,将此文件移动到root文件夹级别。

我发现这个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

3 个答案:

答案 0 :(得分:1)

从以下@Joye的代码中得到了解释。我测试了Joye的代码,它只是给了我“给定格式不支持”错误。不确定这是我的实验室(Powershell V3)。然后我在我的实验室中对它进行了一些修改:

 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))
    }

答案 1 :(得分:0)

如果它们都遵循相同的模式,并且祖父母或root中没有文件,那么这非常简单:

$root = 'C:\root folder'

Get-ChildItem -Recurse |
  ForEach-Object {
    $parent = $_.Parent
    $grandparent = $parent.Parent
    $number = [int]$_.BaseName

    Move-Item $_ -Destination (Join-Path $root ('{0}-{1}-{2}{3}' -f $grandparent, $parent, $number, $_.Extension))
  }

答案 2 :(得分:0)

要获得Great Grandparent,只需添加:

Get-childitem "Y:\DIR\*" -include *.log -recurse |
% {

$nextName = Join-Path -Path 'Y:\DIR\*' -ChildPath $_.name

while(Test-Path -Path $nextName)
{
   $nextName = Join-Path Y:\DIR ($_.BaseName + "_$num" + $_.Extension)    
   $num+=1   
}

$ParentOjbect =$_.Directory
$Parent =$ParentOjbect.Name
$GrandParent = $ParentOjbect.Parent
$GreatGran = $GrandParent.Parent

Copy-item $_ -Destination (Join-Path "Y:\DIR" ('{0}_{1}_{2}_{3}' -f $GreatGran,$GrandParent,$Parent,$_.Name))
}

这对我很有帮助。还要感谢Joye最初创建的Peters修改过的脚本。