开发者

Rename files to increment filenumber using PowerShell?

I've got a bunch of files named

attachment.023940
attachment.024039
attachment.024041
attachment.024103

etc...

I need to rename the files by incrementing the filenumber by a given number. (So that they match the right ID in a database)

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开发者_Go百科 accomplished in PowerShell as well?

I've found several other threads on SO about using PowerShell to rename files, but none of them handled incrementing a filenumber.

I'm on Win7, so PowerShell 2.0 is available.


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)}

This takes advantage of piping into Rename-Item and using scriptblocks with other pipeline bindable parameters like NewName.


Something like this?

$file = Get-ChildItem attachment.012345
$file.basename + ".0" + ([int]::parse([regex]::split($file.extension,"\D")) + 123).tostring()


    PS > attachment.012468


Assuming your filenumbers are all 6 digits, and need to retain the leading zeros:

$increment = 1
gci attachment.$("[0-9]"*6) | sort -descending |% {
$newext = $increment + $_.name.split(".")[1]
rename-item $_.fullname -newname ('attachment.' + "{0:D6}" -f $newext)
} 


I used this to rename my files. Remember that the foreach is a script block, so all you have to do is tack a command at the end to increment your variable, like

PS C:\BigHomie> $A = 1
PS C:\BigHomie> dir .\*.* | Sort-Object | foreach {Rename-Item -Path $_.PSPath -NewName $("Attachment." + "{0:D6}" -f $A);$A=++$A}

Note the $A=++$A at the end which increments your counter, and the D6 number formatter, guaranteeing a 6 width minimum.


Get-ChildItem attachment.* | Move-Item -Destination {
  "attachment.{0}" -f (([int]($_.Name -replace '.*\.(\d+)','$1')) + $increment)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜