Search code examples
windowspowershellbatch-rename

Add special prefix to all files in directory


I have a directory with a certain number of mp3 files, that are sorted by name, for example:

Artist.mp3
Another artist.mp3
Bartist.mp3
Cool.mp3
Day.mp3

How can I add a unique continuous 3-digit prefix to each file, but in a random order, so that when sorting by name it would look something like this:

001 Cool.mp3
002 Artist.mp3
003 Day.mp3
...

Solution

  • Try this:

    $files = Get-ChildItem -File
    $global:i = 0; Get-Random $files -Count $files.Count | 
        Rename-Item -NewName {"{0:000} $($_.Name)" -f ++$global:i} -WhatIf
    

    Or in the unlikely event the filename contains curly braces :-):

    $files = Get-ChildItem -File
    $global:i = 0; Get-Random $files -Count $files.Count | 
        Rename-Item -NewName {("{0:000} " -f ++$global:i) + $_.Name} -WhatIf
    

    Or as @PetSerAl suggests, using [ref]$i as a good way to avoid global vs script scoping issues altogether:

    $files = Get-ChildItem -File
    $i = 0; Get-Random $files -Count $files.Count | 
        Rename-Item -NewName {"{0:000} {1}" -f ++([ref]$i).Value, $_.Name} -WhatIf
    

    If the output looks good remove the -WhatIf and run this again to actually rename the files.