问题
I am trying to make batch file naming easier for my end users. In photographing our locations, we can sometimes have only 1 photo or 500 depending on the size of the location. The code below works beautifully to bulk rename our photos based on how many files are in the directory:
$prefix = "[SomePrefix]"
$files = Get-ChildItem
$id = 1
$files | foreach { Rename-Item -Path $_.fullname -NewName ( $prefix + ((($id++).tostring()).padleft(($files.count.tostring()).length) -replace ' ','0' ) + $_.extension) }
The code pads the photo file name with leading zeroes based on the number of files in the directory, i.e. 1, 2, 3, 4, 5 if the total amount is less than 9 files; 01, 02, 03, 04, 05 if the total amount of files is between 10 and 99; 001, 002, 003, 004, 005 if the total amount of files is between 100 and 999.
I need to modify this code so that it ALWAYS retains 3 leading zeroes 001, 002, 003, 004, 005 no matter the number of files in the directory. However, I do need the code to recurse through the existing directory so I can eliminate users having to organize their photos into different folders based on the number (0-9; 10-99; 100-999) and running separate lines of codes for each.
Example photo file name convention: PREFIX_001.jpg
Can anyone tell me how to modify the above code to suit my needs?
回答1:
PadLeft
isn't needed here.
.ToString("000")
will cause the number to be padded to 3 digits.
see the page on number formatting for some more details here
you could adjust your code to always pad to the minimum required number of digits by doing this:
$Prefix = "[SomePrefix]"
$Files = Get-ChildItem
$PadTo = '0'*$Files.Count.ToString().Length
$ID = 1
$Files | ForEach { Rename-Item -LiteralPath $_.fullname -NewName ($prefix + ($id++).tostring($PadTo) + $_.extension) }
this creates a string $PadTo
which is just a number of 0
's depending on how many files are in your directory, if you have 100-999
files it will have 3 0
's, anything above or below will be 4,5, etc. to match.
回答2:
I'd recommend being careful about square brackets as that can be interpreted as a wildcard of sorts.
$Prefix = '[SomePrefix]'
$Path = '.'
$Folders = Get-ChildItem -LiteralPath $Path -Directory -Recurse
ForEach ($Folder in $Folders)
{
$Counter = 0
Get-ChildItem $Folder -File |
ForEach-Object {
Rename-Item $_.FullName -NewName "${Prefix}_$($Counter.ToString('000'))$($_.Extension)"
$Counter++
}
}
This solution will recursively rename all files in the directories based on the definition of $Path
in the Prefix_001.ext
format
来源:https://stackoverflow.com/questions/45718716/powershell-command-to-bulk-rename-files-sequentially