如何在 PowerShell 中批量重命名文件? [英] How can I bulk rename files in PowerShell?

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

问题描述

我正在尝试执行以下操作:

I'm trying to do the following:

Rename-Item c:\misc\*.xml *.tmp

我基本上想将目录中每个文件的扩展名更改为 .tmp 而不是 .xml.我似乎无法在 PowerShell 中找到一种直接的方法来执行此操作.

I basically want to change the extension on every files within a directory to .tmp instead of .xml. I can't seem to find a straight forward way to do this in PowerShell.

推荐答案

Rename-Item 帮助文档中的示例 4 中检索到的命令:

From example 4 in the help documentation of Rename-Item retrieved with the command:

get-help Rename-Item -examples

示例:

Get-ChildItem *.txt| Rename-Item -NewName { $_.Name -replace '\.txt','.log' }

请注意帮助文档中对替换命令中转义反斜杠的解释,因为它使用正则表达式查找要替换的文本.

要确保正则表达式 -replace 运算符仅匹配字符串末尾的扩展名,请包含正则表达式字符串结尾字符 $.

To ensure the regex -replace operator matches only an extension at the end of the string, include the regex end-of-string character $.

Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$','.log' }

这会处理@OhadSchneider 在评论中提到的情况,我们可能有一个名为 lorem.txt.txt 的文件,我们希望以 lorem.txt 结尾.log 而不是 lorem.log.log.

This takes care of the case mentioned by @OhadSchneider in the comments, where we might have a file named lorem.txt.txt and we want to end up with lorem.txt.log rather than lorem.log.log.

既然正则表达式的目标已经足够紧密,并且受到@etoxin 的回答的启发,我们可以使命令更有用,如下所示:

Now that the regex is sufficiently tightly targeted, and inspired by @etoxin's answer, we could make the command more usable as follows:

Get-ChildItem | Rename-Item -NewName { $_.Name -replace '\.txt$','.log' }

也就是说,如果我们的正则表达式在管道之后进行了充分的过滤,则无需在管道之前进行过滤.并且不再需要在两个地方更改命令字符串(例如,如果您复制上述命令,现在想使用它来更改.xml"文件的扩展名).

That is, there is no need to filter before the pipe if our regex sufficiently filters after the pipe. And altering the command string (e.g. if you copy the above command and now want to use it to change the extension of '.xml' files) is no longer required in two places.

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

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