2017-07-17 164 views
0

标题相同的主题很多,但尝试/修补它们以符合我的需求至今未成功。使用powershell重命名带有文件夹名称和排除项的文件

这与我想实现的接近,但排除不起作用,它重命名所有子文件夹中的PDF文件,而不是唯一剩余的文件夹“文件夹3”。在这里,我尝试了其他主题的解决方案,其中没有一个为我工作到目前为止。

[string[]]$Path = @('C:\test\') 
[string[]]$Excludes = @('*folder 1*', '*Folder 2*') 
Get-ChildItem $Path -Filter *.pdf -Recurse | ?{$_.DirectoryName -notlike $Excludes } | Rename-Item -NewName { $_.Directory.Parent.BaseName + '-' + $_.Name } 

我所试图实现的是重新命名与第一个子文件夹的名称的子文件夹的子文件夹的所有PDF文件,请参见下面的结构。

C:\test\2704814 
\Folder 1 
|- file1.pdf 
|- file2.pdf 
\Folder 2 
|- file1.pdf 
|- file2.pdf 
\Folder 3 
|- file1.pdf 
|- file2.pdf 
C:\test\2704815 
\Folder 1 
|- file1.pdf 
|- file2.pdf 
\Folder 2 
|- file1.pdf 
|- file2.pdf 
\Folder 3 
|- file1.pdf 
|- file2.pdf 

为了得到这个:

C:\test\2704814\Folder 3\2704814-file1.pdf 

C:\test\2704814\Folder 3\2704814-file2.pdf 

回答

2

编辑插入另一个$ ExcludeL1为firstlevel苏bfolders

最安全的方式是做一步一步来:

  • 迭代测试的子文件夹,存储的名称在VAR
  • 迭代子子文件夹和排除不必要的(-notin要求排除文字)
  • 在那里迭代pdf并检查它们是否已经以存储的文件夹名称作为前缀。
  • 终于重命名。

$Base = 'C:\test\' 
$ExcludeL1 = @('folder 1', 'Folder 2') 
$ExcludeL2 = @('Othername') 

Get-ChildITem -Path $Base -Directory | Where {$_.Name -notin $ExcludeL1}|ForEach { 
    $PreFix = $_.Name 
    Get-ChildItem -Path $_.FullName -Directory | 
    Where-Object {$_.Name -notin $ExcludeL2 } | 
     ForEach-Object { 
     Get-ChildItem $_.FullName -Filter *.PDF | 
      Where-Object {$_.BaseName -notmatch $PreFix}| 
      Rename-Item -NewName { "$PreFix-$($_.Name)"} -WhatIf 
     } 
} 

如果你的输出看起来不错,在最后一行删除-WhatIf。我RAMDRIVE一个

样品resutlt:

> tree /F 
A:. 
└───test 
    ├───2704814 
    │ ├───Folder 1 
    │ │  file1.pdf 
    │ │  file2.pdf 
    │ ├───Folder 2 
    │ │  file1.pdf 
    │ │  file2.pdf 
    │ └───Folder 3 
    │   2704814-file1.pdf 
    │   2704814-file2.pdf 
    └───2704815 
     ├───Folder 1 
     │  file1.pdf 
     │  file2.pdf 
     ├───Folder 2 
     │  file1.pdf 
     │  file2.pdf 
     └───Folder 3 
       2704815-file1.pdf 
       2704815-file2.pdf 
+0

您好LotPings,谢谢你的明确的解释和工作方案。奇迹般有效!此外,检查是否已经有一个数字是一个非常受欢迎的添加 – Ignotus

+0

只需创建另一个变量'$ ExcludeL1'(并将另一个变为'$ EcludeL2')并插入一个'Where-Object {$ _。Name -notin $ ExcludeL1} |在第一个Get-ChildItem和ForEach-Object之间。 – LotPings

+0

对不起,删除了另外一个问题,希望你没有那么快;)改成不在,只包含“文件夹3”。将进一步测试,否则尝试更新。谢谢。 – Ignotus