首页 > 解决方案 > 祖父母文件夹名称到文件名

问题描述

我有一个脚本在我指定 c:\script\19\ 的确切目录时运行所有文件的前面。我如何让它查看它正在重命名的文件的祖父母并附加它?它是如何工作的一个例子是这样的文件:

c:\script\18\00000001\Plans.txt
c:\script\19\00001234\Plans.txt
c:\script\17\00005678\App.txt

但是我的脚本正在重命名这样的文件

c:\script\18\00000001\19-0001 Plans.txt
c:\script\19\00001234\19-1234 Plans.txt
c:\script\17\00005678\19-5678 App.txt

我的脚本是这样的:

 $filepath = Get-ChildItem "C:script\" -Recurse |
  ForEach-Object {
$parent = $_.Parent  
$grandparent =  $_.fullname | Split-Path -Parent | Split-Path -Parent | Split-Path -Leaf
    }
Get-ChildItem "C:\Script\" –recurse –file | 
Where-Object {$_.Name –notmatch ‘[0-9][0-9]-[0-9]’} | 
rename-item -NewName {$grandparent + '-' + $_.Directory.Name.SubString($_.Directory.Name.length -4, 4) + ' ' + $_.Name}

标签: powershell

解决方案


最简单的解决方案是将字符串拆分与-split运算符延迟绑定脚本块(您已尝试使用)结合起来:

Get-ChildItem C:\Script –Recurse –File -Exclude [0-9][0-9]-[0-9]* |
  Rename-Item -NewName { 
    # Split the full path into its components.
    $names = $_.FullName -split '\\'
    # Compose the new file name from the relevant components and output it.
    '{0}-{1} {2}' -f $names[-3], $names[-2].Substring($names[-2].Length-4), $_.Name 
  } -WhatIf

-WhatIf 预览重命名操作;删除它以执行实际重命名。
请注意如何-Exclude直接与通配符表达式一起使用Get-ChildItem以排除已经具有目标名称格式的文件。

您的原始文件不起作用的主要原因是您计算了单个、静态 $parent$grandparent值,而不是从每个输入路径派生输入路径特定的值。

此外,您的$grandparent计算是不必要的复杂;Gert Jan Kraaijeveld 的有用答案显示了一种更简单的方法。


推荐阅读