PowerShell - Add grandparent folder name to file name

半世苍凉 提交于 2019-12-12 16:14:33

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/22053364/powershell-add-grandparent-folder-name-to-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!