问题
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 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.
回答1:
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
.
回答2:
Something like this?
$file = Get-ChildItem attachment.012345
$file.basename + ".0" + ([int]::parse([regex]::split($file.extension,"\D")) + 123).tostring()
PS > attachment.012468
回答3:
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)
}
回答4:
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.
回答5:
Get-ChildItem attachment.* | Move-Item -Destination {
"attachment.{0}" -f (([int]($_.Name -replace '.*\.(\d+)','$1')) + $increment)
}
来源:https://stackoverflow.com/questions/4706070/rename-files-to-increment-filenumber-using-powershell