PowerShell Command To Bulk Rename Files Sequentially

被刻印的时光 ゝ 提交于 2019-12-06 11:34:31

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.

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

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