Advertisement
anonit

Batch Rename Files

Sep 18th, 2015
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## BatchRenameFiles.ps1
  2.  
  3. ## Batch renames a directory of files to the same name with number appended.
  4. ## eg
  5. ## Given a directory with files:
  6. ## filea.txt, fileb.txt, filec.txt, etc.
  7. ## Running the command BatchRenameFiles.ps1 -filepath %PATHTOFILES% -renameto Textfile
  8. ## the results would be:
  9. ## Textfile1.txt, Textfile2.txt, Textfile3.txt, etc
  10.  
  11. ## Usage:
  12. ## BatchRenameFiles.ps1 -filepath %PATHTOFILES% -renameto %FILENAME% [-leadingzeros $TRUE/$FALSE]
  13. ## -filepath is the path to the files to be renamed, spaces must be quoted, trailing slash must be added
  14. ## -renameto is the new filename, spaces must be quoted
  15. ## -leadingzeros (optional) is whether or not to pad the numbers out with leading zeros.  Default is $TRUE
  16.  
  17. ## eg:
  18. ## BatchRenameFiles.ps1 -filepath c:\scripts\images\ -renameto "new images"
  19. ## BatchRenameFiles.ps1 -filepath "c:\batch files\VBS\" -renameto images
  20. ## BatchRenameFiles.ps1 -filepath "c:\batch files\VBS\" -renameto images -leadingzeros $FALSE
  21.  
  22.  
  23.  
  24. param(
  25.     [string]$filepath=$(throw "-filepath parameter is required"),
  26.     [string]$renameto=$(throw "-renameto parameter is required"),
  27.     [string]$leadingzeros=$TRUE
  28. )
  29.  
  30. $paddinglength=0
  31. $listoffiles=get-childitem $filepath
  32.  
  33.  
  34. ## Determine if leading zeros are to be added.  If so, set the maximum amount of leading zeros to be used.
  35. if ($leadingzeros -eq $TRUE) {
  36.     $totalfiles=($listoffiles).count
  37.     $paddinglength=($totalfiles.tostring()).length
  38. }
  39.  
  40. $filenumber=1
  41. foreach ($file in $listoffiles)
  42. {
  43.  
  44.     ## Set the padding to nothing.  Determine the length of the current file number.  eg: file1=1, file10=2, etc
  45.     $padding=""
  46.     $fileupto=($filenumber.tostring()).length
  47.  
  48.     ## Add the leading zeros for the specified length.  If -leadingzeros is $false, the length will be zero.
  49.         for ($i=$paddinglength;$i -gt $fileupto; $i--) {
  50.         $padding+="0"
  51.     }
  52.  
  53.     ## Perform the rename, using the padding
  54.     $newname=$renameto+$padding+($filenumber).ToString()+$file.Extension
  55.     rename-item -path $file.fullname -newname $newname
  56.     $filenumber=$filenumber+1
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement