Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding leading zeros to a file name using PowerShell

Tags:

powershell

I have about 1500 files that name with number.jpg. for example, 45312.jpg or 342209.jpg or 7123.jpg or 9898923.jpg or 12345678.jpg

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 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 output is same

$fn = "92454.jpg"
"{0:00000000.jpg}" -f $fn

OR

$fn = "12345.jpg"
$fn.ToString("00000000.jpg")
like image 736
user1497590 Avatar asked Nov 12 '14 00:11

user1497590


2 Answers

'92454.jpg' | % PadLeft 12 '0'

Or

'92454.jpg'.PadLeft(12, '0')

Result

00092454.jpg

PadLeft Method

like image 76
Zombo Avatar answered Sep 28 '22 11:09

Zombo


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}
like image 33
TheMadTechnician Avatar answered Sep 28 '22 10:09

TheMadTechnician