Reputation: 145
I have about 1500 files that have the name <number>.jpg. For example, 45312.jpg, 342209.jpg, 7123.jpg, 9898923.jpg, or 12345678.jpg
The total number before the extension should be 8 digits. So I need to add leading zeros for if it less than 8 digit to make an 8-digits file name.
00001234.jpg
00012345.jpg
00123456.jpg
01234567.jpg
I tried this PowerShell script, but it's complaining.
I tried this, but the output is the same
$fn = "92454.jpg"
"{0:00000000.jpg}" -f $fn
OR
$fn = "12345.jpg"
$fn.ToString("00000000.jpg")
Upvotes: 8
Views: 14114
Reputation: 1
'92454.jpg' | % PadLeft 12 '0'
Or
'92454.jpg'.PadLeft(12, '0')
Result
00092454.jpg
Upvotes: 11
Reputation: 36297
You had it right, but the {0:d8} only works on numbers, not strings, so you need to cast it correctly.
Get-ChildItem C:\Path\To\Files | Where{$_.basename -match "^\d+$"} | ForEach{$NewName = "{0:d8}$($_.extension)" -f [int]$_.basename;rename-item $_.fullname $newname}
Upvotes: 7