本文介绍了使用 PowerShell 向文件名添加前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有大约 1500 个以 number.jpg 命名的文件.例如,45312.jpg 或 342209.jpg 或 7123.jpg 或 9898923.jpg 或 12345678.jpg
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
分机前的总号码应为 8 位数字.所以我需要添加前导零,如果它小于 8 位来制作 8 位文件名.
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
我尝试了这个 powershell 脚本,但它在抱怨.
I tried this powershell script but it's complaining.
我试过了,但输出是一样的
I tried this but output is same
$fn = "92454.jpg"
"{0:00000000.jpg}" -f $fn
或
$fn = "12345.jpg"
$fn.ToString("00000000.jpg")
推荐答案
你说得对,但 {0:d8} 只对数字有效,对字符串无效,所以你需要正确地转换它.
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}
这篇关于使用 PowerShell 向文件名添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!