Search code examples
windowspowershellfilepadleft

Windows PowerShell, PadLeft


i need to make files name string like text_000.txt, where 000 should increase every file but i got problem like this where after 10 iterations the digits in the file name become more than necessary

i need to get file name like "text_001.mp3" and it's ok for 9 files, but after i got "text_0010"

this is code

*param (
[string]$dir = "C:\Users\Администратор\Desktop\music"
)
Set-Location -Path $dir
$count=1
Get-ChildItem -Path $dir | Sort-Object -Property LastWriteTime | % { Rename-Item $_ -NewName (‘text' + '{0}'.PadLeft(5,"0") -f $count++ + '.txt') }*

Solution

  • It is probably easier to directly format your filename number with leading zeros, like:

    'text_{0:000}.txt' -f [int]$Count
    

    e.g.:

    'text_{0:000}.txt' -f 17
    text_017.txt
    

    Also knowing that this will properly overflow (prevent duplicate filenames):

    'text_{0:000}.txt' -f 1234
    text_1234.txt
    

    In your case:

    ... | Foreach-Object { Rename-Item $_ -NewName ('text_{0:000}.txt' -f $count++) }