使用PowerShell重命名文件以增加文件号? [英] Rename files to increment filenumber using PowerShell?
问题描述
我有一堆名为
attachment.023940
attachment.024039
attachment.024041
attachment.024103
等...
我需要通过将文件编号增加给定编号来重命名文件. (以便它们与数据库中的正确ID相匹配)
I need to rename the files by incrementing the filenumber by a given number. (So that they match the right ID in a database)
我想我可以编写一个使用RegEx解析文件名的C#应用程序,但是我认为这也是可以在PowerShell中完成的任务?
I guess I could write a C# application that uses RegEx to parse the filename, but I assume this is a task that could be accomplished in PowerShell as well?
我在SO上发现了其他几个有关使用PowerShell重命名文件的线程,但是没有一个线程可以处理增加文件号的问题.
I've found several other threads on SO about using PowerShell to rename files, but none of them handled incrementing a filenumber.
我在Win7上,因此可以使用PowerShell 2.0.
I'm on Win7, so PowerShell 2.0 is available.
推荐答案
由于数字位于文件名的Extension
部分中,因此以下方法起作用了.
The following approach happens to work because the number is in the Extension
part of the filename.
Get-ChildItem attachment.* | Sort Extension -desc |
Rename-Item -NewName {$_.basename +
".{0:D6}" -f ([int]$_.extension.substring(1) + 1)}
这利用了管道输送到Rename-Item
以及将脚本块与其他管道可绑定参数(例如NewName
)一起使用的优势.
This takes advantage of piping into Rename-Item
and using scriptblocks with other pipeline bindable parameters like NewName
.
这篇关于使用PowerShell重命名文件以增加文件号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!