Search code examples
powershellscriptingpathfile-rename

PowerShell - Add grandparent folder name to file name


I'm still pretty new at PS Scripting, so most of what I do is hacked together from examples. What I'm trying to do right now is search all the folders in a directory for PDFs and then rename them, adding the grandparent folder name to the file name. For example:

c:\export\123\notes\abc.pdf would be renamed to c:\export\123\notes\123_abc.pdf

The rest of the script, which works fine, uses GhostScript to convert them to TIFs and moves them to another server. The problem is that that all the PDFs are named similarly, but the '123' folder is unique for the documents. Here's what I've managed to scrape together:

Get-ChildItem 'c:\export\' -Recurse *.pdf |
  ForEach-Object {
  $parent = $_.Parent
  $grandparent = $parent.Parent

  Rename-Item -NewName {$_.$grandparent + "_" + $_.Name}
  }

The script is throwing an error at the '-NewName' parameter, which I've tried removing but that doesn't work. I've tried to copy code that will add the parent folder to the file name, but I can't seem to get finding the grandparent folder name AND adding the name to the file working together.


Solution

  • Does this work better?

    $GrandParent = 
     $_.fullname | Split-Path -Parent | Split-Path -Parent | Split-Path -Leaf
    

    You need to split off the parent path twice, then split the leaf off of that to get just the grandparent folder name without the rest of the path.