title: Rename Files to include Parent & Grantparent folder - powershell
body: <p>I have folders that follow the pattern like this:</p>
  
  <pre><code>C:\root folder\grandparent folder\parent folder\00001.pdf
  C:\root folder\grandparent folder\parent folder\00002.pdf
  </code></pre>
  
  <p>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.</p>
  
  <p>I found this powershell script that does something similar but it only takes the parent folder name.</p>
  
  <p>This is what i have:</p>
  
  <pre><code>#######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
  </code></pre>