使用 PowerShell 重命名文件 [英] Renaming Files with PowerShell

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

问题描述

我需要在 Windows PowerShell 中一次重命名一堆文件.我阅读了 HTG 文章 在这里,它有点帮助.

I need to rename a bunch of files at once in Windows PowerShell. I read the HTG article here and it helped a little.

我的问题是它只会重命名目录顶部的文件,不会更深.例如:有 FOLDER A,在 FOLDERA 里面是一个文件,在 FOLDER B 里面是另一个文件.两个文件夹和两个文档都需要重命名.现在的工作方式是文件夹 A、文件夹 A 中的文档和文件夹 B 正在重命名,但文件夹 B 中的文档没有重命名.

My problem is that It will only rename files in the top of the directory, nothing deeper. For example: There is FOLDER A and inside FOLDERA is a document and FOLDER B. Inside FOLDER B is another document. Both folders and both documents need to be renamed. The way it is working now is that FOLDER A, the document in FOLDER A, and FOLDER B are being renamed, but not the document inside FOLDER B.

我当前的代码是:

Dir | Rename-Item –NewName { $_.name –replace " ","_" }

感谢您的帮助!

推荐答案

您需要在 Dir 上指定 -Recurse 参数以使其递归,例如:

You need to specify the -Recurse parameter on Dir to get it to recurse e.g.:

Dir -recurse | Rename-Item -NewName {$_.Name -replace ' ','_'}

顺便说一句,这可能会遇到问题,因为您首先重命名包含文档的文件夹 (FOLDERB),但与 FOLDERB 中的文件相对应的管道项目仍然具有旧名称.在这种情况下,您希望自下而上重命名.一种非常粗略但有效(我认为)的方法是按路径长度降序对文件项进行排序,例如:

BTW this may run into a problem because you're renaming the folder (FOLDERB) that contains the document first but the item being piped that corresponds to the file in FOLDERB still has the old name. In this case, you want to rename from the bottom up. One very crude but effective (I think) way to do this is to sort the file items on their path length descending e.g.:

Dir -recurse | Sort {$_.FullName.Length} -Desc | Rename-Item {$_.Name -replace ' ','_'}

这篇关于使用 PowerShell 重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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