Adding leading zeros to a file name using PowerShell

纵饮孤独 提交于 2021-02-18 22:20:46

问题


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

回答1:


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}



回答2:


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

Or

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

Result

00092454.jpg

PadLeft Method



来源:https://stackoverflow.com/questions/26877248/adding-leading-zeros-to-a-file-name-using-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!