powershell - 在 Powershell 中将文件重命名为小写

标签 powershell rename recursive-descent

我正在尝试使用 Powershell 2.0 递归地重命名一堆文件。目录结构如下所示:

Leaflets
+ HTML
  - File1
  - File2
  ...
+ HTMLICONS
  + IMAGES
    - Image1
    - Image2
  - File1
  - File2
  ...
+ RTF
  - File1
  - File2
  ...
+ SGML
  - File1
  - File2
  ...

我正在使用以下命令:
get-childitem Leaflets -recurse | rename -newname { $_.name.ToLower() }

它似乎重命名文件,但提示子目录:
Rename-Item : Source and destination path must be different.

我每月使用 robocopy 重新加载数据,但目录不会更改,因此我可以手动重命名它们。有什么办法可以拿到get-children跳过子目录(如 find Leaflets -type f ... )?

谢谢。

更新:问题似乎出在已经全部小写的文件上。我尝试将命令更改为:
get-childitem Leaflets -recurse | if ($_.name -ne $_name.ToLower()) rename -newname { $_.name.ToLower() }

但现在 Powershell 提示 if不是 cmdlet、函数等。
我可以通过管道传输 get-childitem 的输出吗?到 if陈述?

更新 2 :这有效:
$files=get-childitem Leaflets -recurse
foreach ($file in $files)
{
    if ($file.name -ne $file.name.ToLower())
    {
        rename -newname { $_.name.ToLower() }
    }
}

最佳答案

尽管您已经发布了自己的答案,但这里有一个变体:

dir Leaflets -r | % { if ($_.Name -cne $_.Name.ToLower()) { ren $_.FullName $_.Name.ToLower() } }

几点:
  • 目录 的别名Get-ChildItem (并且 -r 是 -Recurse 的缩写)。
  • % 的别名ForEach-Object .
  • -cne 是区分大小写的比较。 -ne 忽略大小写差异。
  • $_ 是您在 ForEach-Object 循环中引用当前项目的方式。
  • 的别名重命名项目 .
  • 全名 可能是首选,因为它确保您将接触到正确的文件。

  • 如果您想从重命名中排除目录,您可以包含以下内容:
    if ((! $_.IsPsContainer) -and $_.Name -cne $_.Name.ToLower()) { ... }
    

    希望这有助于继续学习和探索 PowerShell。

    关于powershell - 在 Powershell 中将文件重命名为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3822745/

    相关文章:

    linux - 文件内部批量重命名,包括子目录

    parsing - 句法分析和语义分析

    haskell - 是否有更可维护的方法来处理我的数据类型?

    c++ - 基于 EBNF 语法的 C++ 下降递归解析器实现

    PowerShell - 将 CSV 转换为 XLSX

    xml - Powershell:搜索用 CSV 替换 XML

    c# - Powershell 添加脚本并从 C# 调用不在命令行上显示结果

    c - 在 Linux 中使用重命名来安全地覆盖共享文件

    linux - 使用 mv 从文件中删除前缀和后缀

    PowerShell Active Directory IF 语句