Share via


PowerShell Tip: Bulk Renaming Files

Summary

This wiki is reference to the forum post Copy and Edit Files What's new in renaming files using PowerShell. Nothing is new but requirement and scenario differs. I would like to share my day to day learning of PowerShell and some guides which I refer.

Requirement

Copy the files from source directory to destination directory Rename Files if the length is greater than 10  

Practice

help Rename-Item -Detailed 
 
help Copy-Item -Detailed 
 
help about_Foreach -Detailed 
 
help Where-Object -Detailed 
 
help Get-ChildItem -Detailed

Explanation

When you need to seek help for PowerShell Commands. You can get it yourself before you Google or Bing How? and Where? Let's consider this forum post requirement. We need to copy and rename files. I used the below method to achieve this task Copy File Items

Get-Command -Verb Copy

Rename File Items

Get-Command -Verb Rename

The output will be bunch of functions and cmdlets available in your machine :). PowerShell is huge we can't remember all the commands. So now how to rename the files if name is greater than 10 and skip if not.

Code

$source = 'C:\Temp\Test\*.txt'            
$destination = "C:\Temp\Test1\"            
Copy-Item -Path $source -Destination $destination -Force            
            
$files = Get-ChildItem -Recurse -Filter "*.txt"            
$nr = 1            
$files | % {            
            
    If ($_.BaseName.Length -gt 10) {            
                
        Rename-Item -Path $_.Name -NewName $($_.BaseName.Substring(0,10) + '__{0:D1}' -f ($nr++) + $_.Extension )            
                
    }             
                
}

Enjoy PowerShell :)  

Others Languages 

This article is also available in the following languages: