Search code examples
powershellloopsif-statementrename

Powershell to rename files to incrementing numbers, add prefix zeroes depending on the current number value


I'm trying to organize my picture files, so that they will be named in order as such: 001, 002, ..., 010, 011, ..., 100, 101, ...

I was able to get a code that iterates each file, and renames each of them to increasing number: 1, 2, 3, 4, ...

I can also manually add "0" or "00" before it.

What I want is to add "00" if the current number is <10, add "0" if current number is >=10 && <100 and add nothing if current number is >100

Problem is I have no idea how to implement the if statements in Powershell loop. Here is what I was able to find:

$nr = 1
Dir | %{Rename-Item $_ -NewName (‘00{0}.jpg’ -f $nr++)}

It it even possible to add "If" statement in such a loop? I have almost no experience with Powershell at all.


Solution

  • You can use the D format specifier for your integer. See Standard format specifiers for more information.

    Example:

    0..50 | ForEach-Object { $_.ToString('D3') }
    
    # Also valid using `String.Format` (`-f` operator in PowerShell)
    0..50 | ForEach-Object { '{0:D3}' -f $_ }
    

    Applied to your code:

    $nr = 1
    Get-ChildItem | ForEach-Object { $_ | Rename-Item -NewName ('{0:D3}.jpg' -f $nr++) }