在Powershell中将文件重命名为小写 [英] Rename files to lowercase in Powershell

查看:225
本文介绍了在Powershell中将文件重命名为小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to rename a bunch of files recursively using Powershell 2.0. The directory structure looks like this:

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

我正在使用以下命令:

get-childitem Leaflets -recurse | rename -newname { $_.name.ToLower() }

似乎重命名了文件,但抱怨子目录:

and it seems to rename the files, but complains about the subdirectories:

Rename-Item : Source and destination path must be different.

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

I reload the data monthly using robocopy, but the directories do not change, so I can rename them by hand. Is there any way to get get-children to skip the subdirectories (like find Leaflets -type f ...)?

谢谢.

更新:看来问题出在已经都是小写的文件上.我尝试将命令更改为:

UPDATE: It appears that the problem is with files that are already all lower case. I tried changing the command to:

get-childitem Leaflets -recurse | if ($_.name -ne $_name.ToLower()) rename -newname { $_.name.ToLower() }

,但现在Powershell抱怨if不是cmdlet,函数等. 我可以将get-childitem的输出传递给if语句吗?

but now Powershell complains that if is not a cmdlet, function, etc. Can I pipe the output of get-childitem to an if statement?

更新2 :有效:

$files=get-childitem Leaflets -recurse
foreach ($file in $files)
{
    if ($file.name -ne $file.name.ToLower())
    {
        rename -newname { $_.name.ToLower() }
    }
}

推荐答案

即使您已经发布了自己的答案,也可以使用以下变体:

Even though you have already posted your own answer, here is a variation:

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

一些要点:

  • dir Get-ChildItem 的别名(-r是-Recurse的缩写).
  • ForEach-Object 的别名.
  • -cne 是区分大小写的比较. -ne 忽略大小写差异.
  • $ _ 是在ForEach-Object循环中引用当前项目的方式.
  • ren 重命名项的别名.
  • 全名可能是首选,因为它可以确保您触摸正确的文件.
  • dir is an alias for Get-ChildItem (and -r is short for -Recurse).
  • % is an alias for ForEach-Object.
  • -cne is a case-sensitive comparison. -ne ignores case differences.
  • $_ is how you reference the current item in the ForEach-Object loop.
  • ren is an alias for Rename-Item.
  • FullName is probably preferred as it ensures you will be touching the right file.

如果您想排除目录的重命名,则可以包含以下内容:

If you wanted to excludes directories from being renamed, you could include something like:

if ((! $_.IsPsContainer) -and $_.Name -cne $_.Name.ToLower()) { ... }

希望这对继续学习和探索PowerShell很有帮助.

Hopefully this is helpful in continuing to learn and explore PowerShell.

这篇关于在Powershell中将文件重命名为小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆