简体   繁体   中英

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.

On PowerShell v3 and newer you can use the item's Parent property:

Get-ChildItem 'c:\export\' -Recurse *.pdf | % {
  Rename-Item -NewName {$_.Parent.Parent.Name + "_" + $_.Name}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM