【问题标题】:Rename files with foldername and exclusions using powershell使用 powershell 重命名带有文件夹名和排除项的文件
【发布时间】:2017-07-17 13:57:03
【问题描述】:

有很多标题相同的主题,但尝试/修改它们以适应我的需求迄今为止没有成功。

这接近我想要实现的目标,但排除不起作用,它重命名所有子文件夹中的 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

等等

【问题讨论】:

    标签: powershell pdf subdirectory batch-rename


    【解决方案1】:

    EDIT 为一级子文件夹插入了另一个 $ExcludeL1

    最安全的方法是一步一步来:

    • 迭代test的子文件夹,将名称存储在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 A 上的示例结果:

    > 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
    

    【讨论】:

    • 您好 LotPings,感谢您提供清晰的解释和有效的解决方案。奇迹般有效!此外,检查是否已经有号码是非常受欢迎的补充
    • 只需创建另一个变量$ExcludeL1(并将另一个重命名为$EcludeL2)并在第一个Get-ChildItem 和ForEach-Object 之间插入一个Where-Object {$_.Name -notin $ExcludeL1 } |
    • 抱歉,删除了另一个问题,希望你没那么快 ;) 将 notin 更改为 in 并仅包含“文件夹 3”。将进一步测试,否则尝试您的更新。谢谢。
    • 更新:也可以使用 -in 参数。
    • 你将变量命名为 $Include 然后 :-)
    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 2016-02-27
    • 2021-04-13
    • 1970-01-01
    • 2014-09-09
    • 2012-12-24
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多