I've used ChatGPT to write me a script to rename a portion of a file name from "SF78" to "Medical" and add a sequence (1) etc to the end of the file name. Unfortunately, it's not 100% successful. The sequence is being added after the file extension.
I've tried to use $file.BaseName as to not include the extension, then add the extension after joining the $file.basename, sequence, and then the file extension. Nothing seems to work. It's got to be the smallest setting at a specific place as I get so close, but just can't get it right.
This is the script:
```
$folderPath = $filePath
$files = Get-ChildItem -Path $folderPath -File | Where-Object { $_.Name -match 'SF78' }
foreach ($file in $files) {
$originalName = $file
$newName = $originalName -replace 'SF78', 'MEDICAL'
# Check if a file with the new name already exists
$counter = 1
while (Test-Path (Join-Path -Path $folderPath -ChildPath $newName)) {
$testName = $originalName -replace 'SF78', 'MEDICAL'
$newName = (($testName, ($counter)) -join ' ') + $file.extension
$counter++
}
# Rename the file
$newPath = Join-Path -Path $folderPath -ChildPath $newName
Rename-Item -Path $file.FullName -NewName $newName
Write-Host "Renamed $($originalName) to $($newName)"
}
```