File Renaming Script
In this post, we present a PowerShell script that automates the process of renaming files in a specific directory based on a defined naming convention. This script is especially helpful for organizing files systematically.
If you are interested in improving your server management processes, be sure to check out 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 where the files to be renamed are located, as well as the new naming convention to be applied.
$targetDirectory = 'C:\FilesToRename' $newFilePrefix = 'Document_' $fileExtension = '.txt'
### Step 2: Retrieve Files for Renaming
Next, the script collects the files from the specified directory that match the desired file type. This makes it easier to apply the renaming logic only to relevant files.
$filesToRename = Get-ChildItem -Path $targetDirectory -Filter "*$fileExtension" -File
### Step 3: Rename Files Based on the New Convention
In this step, we loop through the collected files and rename each one according to the defined prefix and an incremental number. This ensures that each file is uniquely named.
$count = 1 foreach ($file in $filesToRename) { $newFileName = "${newFilePrefix}${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 that informs the user of how many files were renamed during the operation, offering clear feedback on the outcome.
Write-Host "File renaming process completed. $($count - 1) files were renamed in '$targetDirectory'."
Feel free to adjust the target directory and naming convention to fit your needs. This script is a great way to keep your files organized! Keep an eye on our website for more useful PowerShell scripts.