PowerShell-将祖父母文件夹名称添加到文件名 [英] PowerShell - Add grandparent folder name to file name

查看:114
本文介绍了PowerShell-将祖父母文件夹名称添加到文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是PS Scripting的新手,所以我所做的大部分工作都是从示例中学习到的.我现在想要做的是在目录中的所有文件夹中搜索PDF,然后重命名它们,将祖父母文件夹名称添加到文件名中.例如:

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将重命名为c:\ export \ 123 \ notes \ 123_abc.pdf

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

该脚本的其余部分运行正常,使用GhostScript将其转换为TIF并将其移至另一台服务器.问题在于所有PDF都以类似的方式命名,但是'123'文件夹对于文档而言是唯一的.这是我设法拼凑的:

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

该脚本在'-NewName'参数上引发了错误,我尝试删除该参数,但这不起作用.我试图复制将父文件夹添加到文件名的代码,但似乎找不到祖父母文件夹名并将其添加到文件中.

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.

推荐答案

这样做更好吗?

$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.

这篇关于PowerShell-将祖父母文件夹名称添加到文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆