0

次のようなパターンに従うフォルダーがあります。

C:\root folder\grandparent folder\parent folder\00001.pdf
C:\root folder\grandparent folder\parent folder\00002.pdf

PDFの名前をルートフォルダー-祖父母フォルダー-親フォルダー.1.pdfやルートフォルダー-祖父母フォルダー-親フォルダー.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
4

3 に答える 3

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))
    }
于 2013-07-24T23:50:11.597 に答える
0

それらがすべて同じパターンに従っていて、祖父母またはルートにファイルがない場合、それは非常に簡単です:

$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))
  }
于 2013-07-24T12:14:32.230 に答える