祖父母文件夹名称到文件名称

时间:2019-01-18 15:49:10

标签: powershell

我有一个脚本,当我指定c:\ script \ 19 \的确切目录时会运行,问题是,c:\ script中有其他文件夹,例如18、17、16。我要追加的脚本所有文件前面的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}

2 个答案:

答案 0 :(得分:2)

要获取$ file对象的祖父母:

$file.Directory.Parent

文件的父目录是文件对象的“目录”成员。

目录的父目录是目录对象的“父级”成员。

这并不难,但可以肯定的是使它困惑...


修改

您要求我的解决方案:

Get-ChildItem C:\script -Recurse -File | ForEach-Object {
  $parent = $_.Directory.Name
  $grandparent = $_.Directory.Parent.Name
  Rename-Item $_.FullName -NewName "$grandparent-$($parent.Substring($parent.length-4,4)) $($_.name)" 
}

我使用Get-ChildItem的-file参数仅从文件夹结构中获取文件。我不确定这是否适合您的情况

答案 1 :(得分:2)

最简单的解决方案是将字符串拆分与-split operatordelay-bind script block(您尝试使用)结合使用:

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 预览重命名操作;删除它以执行实际的重命名。
请注意如何将-ExcludeGet-ChildItem一起直接与通配符表达式一起使用,以排除已经具有目标名称格式的文件。

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

此外,您的$grandparent计算不必要地复杂; Gert Jan Kraaijeveld's helpful answer显示了一种更简单的方法。

相关问题