Search code examples
powershellnumbersadditionfilenamesoffset

Powershell offset number in name of multiple files by a constant


I have multiple files from camera with names "00010001", "00010002", etc. Those are multiple file types (JPG, CR2, xmp, MOV) in one folder (lets say C:\camera).

I need to add 10000 to number in all file names, so it becomes "00020001", "00020002", etc. I guess this could be done with a simple script in powershell, but I have absolute no experience with it. I would be very grateful if someone helped me with it. Thank you.


Solution

  • If the code should also handle files in subfolders of 'C:\Camera', you can use the -Recurse and -Include parameters:

    (Get-ChildItem -Path 'C:\Camera' -File -Include '*.JPG','*.CR2','*.XMP','*.MOV' -Recurse) | 
        Where-Object { $_.BaseName -match '\d{8}' } | 
        Rename-Item -NewName { '{0:D8}{1}' -f ([int]$_.BaseName + 10000), $_.Extension } -WhatIf
    

    If however this should NOT go any deeper that the root folder 'C:\Camera', then do this:

    (Get-ChildItem -Path 'C:\Camera' -File) | 
        Where-Object { $_.BaseName -match '\d{8}' -and $_.Extension  -match '\.(JPG|CR2|XMP|MOV)$' } | 
        Rename-Item -NewName { '{0:D8}{1}' -f ([int]$_.BaseName + 10000), $_.Extension } -WhatIf
    

    Once you are satisfied the code would create the new filenames as you wish, remove the safety switch -WhatIf

    Explanation:

    • Get the files in the folder that have BaseNames consisting of 8 digits ($_.BaseName -match '\d{8}') and that have an extension of either JPG, .CR2, .XMP or .MOV
    • Convert that BaseNaem into an interger number and add 10000
    • Reassemble the file name with the -f format operator, where the template string {0:D8}{1} makes sure all (new) numbers are prefixed with zeroes up to 8 digits