【问题标题】:How to rename files with a conditional statement in PowerShell如何在 PowerShell 中使用条件语句重命名文件
【发布时间】:2020-02-13 04:53:42
【问题描述】:

我正在尝试重命名位于一个文件夹中但位于不同子文件夹中的大量文件。应重命名文件,使其名称由文件夹名 + 原始文件名组成。我想知道您是否可以添加条件语句,以便在文件名已包含文件夹名称时文件名不会更改。下面的代码执行重命名文件的功能,但不包含 if 语句。

dir -recurse | Rename-Item -NewName {$_.Directory.Name + " - " + $_.Name}

下面的代码是我想象的代码外观的示例:

dir -recurse | if($_.Name -contains $_.Directory.Name) {Rename-Item -NewName {$_.Directory.Name + " - " + $_.Name}}

【问题讨论】:

标签: powershell


【解决方案1】:

应该这样做:

$rootFolder = 'D:\test'
Get-ChildItem -Path $rootFolder -File -Recurse | ForEach-Object {
    $folder = $_.Directory.Name
    if (!($_.Name.StartsWith($folder))) { $_ | Rename-Item -NewName ('{0} - {1}' -f $folder, $_.Name) }
}

【讨论】:

    【解决方案2】:

    Theo's answer 效果很好,但还有一个替代方案,它在概念上更简单,性能明显更好:

    您可以利用将未更改文件名传递给-NewName是一个安静的无操作这一事实,因此您可以将所有逻辑放在-NewName 脚本块:

    Get-ChildItem -File -Recurse |
      Rename-Item -NewName { 
        if ($_.Name -like ($_.Directory.Name + ' - *') { # already renamed
          $_.Name # no change
        }
        else { # rename
          $_.Directory.Name ' - ' + $_.Name
        }
      } -WhatIf
    

    -WhatIf预览重命名操作;删除它以执行实际重命名。

    而不是在其脚本块中使用 ForEach-Object 调用和嵌套的 Rename-Item 调用 - 这意味着 Rename-Item 被调用每个输入文件一次 - 此解决方案使用 带有 single Rename-Item 调用的单个 管道,其中新名称(如果更改)通过 delay-bind 脚本块确定 - 请参阅 this answer了解详情。

    【讨论】:

      【解决方案3】:

      我尝试的方式与提出问题的方式接近。我希望我不必添加另一个 foreach。

      dir -recurse -file | & { 
        foreach ($i in $input) {
          if(-not ($i.Name.contains($i.Directory.Name))) {
            Rename-Item $i.fullname -NewName ($i.Directory.Name + ' - ' + $i.Name) -whatif 
          } 
        } 
      }
      

      或者像这样

      dir -recurse -file | % { 
        if(-not ($_.Name.contains($_.Directory.Name))) {
          Rename-Item $_.fullname -NewName ($_.Directory.Name + ' - ' + $_.Name) -whatif 
        } 
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-26
        • 1970-01-01
        • 2018-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-19
        • 2011-07-31
        • 2021-08-27
        相关资源
        最近更新 更多