- 1 year ago
PowerShell - Renaming files that have the same basename
You can use PowerShell to rename files that have the same basename by iterating through the files in the directory and appending a number to the basename of each file to make it unique. Here's an example script that you can use:
php$dir = "C:\path\to\directory"
$files = Get-ChildItem -Path $dir -File
foreach ($file in $files) {
$basename = $file.BaseName
$extension = $file.Extension
$i = 1
while (Test-Path "$dir\$basename$i$extension") {
$i++
}
Rename-Item $file.FullName -NewName "$basename$i$extension"
}
In this example, the script sets the directory to search for files using the $dir
variable, and retrieves a list of files in the directory using the Get-ChildItem
cmdlet with the -File
parameter. The script then iterates through each file in the directory and appends a number to the basename to make it unique.
The while
loop checks if a file with the same name already exists in the directory. If it does, the loop increments the counter and checks again until it finds a unique name. Finally, the script renames the file using the Rename-Item
cmdlet with the -NewName
parameter.
By using this script, you can rename files in a directory that have the same basename, ensuring that each file has a unique name.