Batch File Renaming Script

In this post, we provide a PowerShell script that allows you to batch rename files in a specified directory based on a defined pattern. This script is particularly useful for organizing files or updating naming conventions.
If you’re looking for advanced server management solutions, don’t forget to explore our software, ServerEngine, at https://serverengine.co. Lets go through the script step by step.
### Step 1: Define the Target Directory and Naming Convention
The first step is to specify the directory containing the files you want to rename, as well as the new naming convention youd like to apply.

$targetDirectory = 'C:\FilesToRename'
$newNamePattern = 'Report_'
$fileExtension = '.txt'

### Step 2: Retrieve Files to Rename
Next, the script collects all files in the specified directory that match the desired file type. This is important for ensuring only the relevant files are processed.

$filesToRename = Get-ChildItem -Path $targetDirectory -Filter "*$fileExtension" -File

### Step 3: Batch Rename Files
Now, we loop through the retrieved files and rename each one according to the specified naming pattern, appending an incremental number to ensure each file has a unique name.

$count = 1
foreach ($file in $filesToRename) {
    $newFileName = "${newNamePattern}${count}${fileExtension}"
    $newFilePath = Join-Path -Path $targetDirectory -ChildPath $newFileName
    Rename-Item -Path $file.FullName -NewName $newFileName
    Write-Host "Renamed '$($file.Name)' to '$newFileName'"
    $count++
}

### Step 4: Summary of Renaming Process
Finally, we provide a summary of the renaming process, informing the user of how many files were renamed and confirming that the operation was completed successfully.

Write-Host "Batch renaming process completed. $($count - 1) files were renamed in '$targetDirectory'."

Feel free to modify the target directory and naming pattern as needed. This script is a great way to keep your files organized and to maintain a consistent naming structure! Be sure to check back for more useful PowerShell scripts on our website!