0

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)"
}
```
2
  • what happens with this current code? is it not renaming? is it giving an error? Commented Jan 18, 2024 at 4:49
  • As I was trying different ways to get the basename and add the sequence to that, I'd either only get the sequence number with or without the parenthesis and no part of the file name at all. Or I'd get the entire file name with the sequence after the file extension. I just couldn't get the sequence at the end of the file basename and before the extension. The modified script from "The Freelancer" works perfectly. Commented Jan 18, 2024 at 14:40

2 Answers 2

0

Try with this script. I have modified it

$folderPath = $filePath

$files = Get-ChildItem -Path $folderPath -File | Where-Object { $_.Name -match 'SF78' }

foreach ($file in $files) {
    $originalName = $file.Name
    $basename = $file.BaseName
    $extension = $file.Extension

    $newName = $basename -replace 'SF78', 'MEDICAL'

    # Check if a file with the new name already exists
    $counter = 1
    while (Test-Path (Join-Path -Path $folderPath -ChildPath "$newName$extension")) {
        $newName = "$basename ( $counter )"  # Add sequence within parentheses before extension
        $counter++
    }

    # Rename the file
    $newPath = Join-Path -Path $folderPath -ChildPath "$newName$extension"
    Rename-Item -Path $file.FullName -NewName $newPath
    Write-Host "Renamed $($originalName) to $newName"
}
Sign up to request clarification or add additional context in comments.

4 Comments

Good morning "The Freelancer" from Oregon. This mod worked perfectly. I'm absorbing what you've done, noticing where you pulled the file name apart, added the sequence, and put it all back together. Greatly appreciated for both the fix, the lesson, and most importantly your time to assist. Have a great day.
Correction. My early morning eyes didn't catch the fact that the new name still shows "SF78" instead of "MEDICAL" while still adding the sequence "(1)" to the name. Thus the new name shows "1234_SF78_ABCD (1).PDF" instead of "1234_MEDICAL_ABCD.PDF" because the existing "medical" PDF already existed. The sequence is in the right place now, so I'm sure I can fix the name part.
Final little bug is fixed. Directly under the line "while...", changed "$newName = "basename...." to "#newName = "newName...." and the new name was perfect. Once again, thanks again for your assistance.
@JeffR Glad to hear that the solution was working fine for you. Thank you for your valuable feedback. Now you can mark this as an Answer.
0

UPDATED ANSWER

# Get all the files which name starts with SF78
Get-ChildItem -Path $Path -File -Filter *SF78* |
    ForEach-Object {
        
        # Write-Warning "here"
        $NewBaseName = $_.BaseName -replace 'sf78', 'medical'
        $CountMedicalFiles = (Get-ChildItem -Path $path -File -Filter "$NewBaseName*").count

        # If there is no file named MEDICAL*
        ## set the name of the new file to MEDICAL
        ## increase the count of the files named MEDICAL* of 1
        if (0 -eq $CountMedicalFiles) {
            $NewName = '{0}{1}' -f $newbasename, $_.Extension
            # $CountMedicalFiles++    
        }
        # If there is at least 1 file named MEDICAL
        ## set the name of the new file to MEDICAL (N), where N depnds on the count of existing MEDICAL files
        else {
            # change this to set what number is the first you want between parenthesis.
            # -1 for (0), 0 for (1), 1 for (2) etc
            $BaseNumber = 0
            $NewName = '{0} ({1}){2}' -f $newbasename, ($BaseNumber + $CountMedicalFiles++), $_.Extension
        }
        # rename the file using the full path so it's certainly set in the same directory as the original file.
        Rename-Item -LiteralPath $_.FullName -NewName $NewName 
        
        Write-Host ('Renamed {0} to {1}' -f $_.Name, $NewName)
    }

OLD ANSWER: I've tried the simplest approach I could.

# Get the amount of files which name starts with MEDICAL*
$CountMedicalFiles = (Get-ChildItem -Path $Path -File -Filter MEDICAL*).count

# Get all the files which name starts with SF78
Get-ChildItem -Path $Path -File -Filter SF78* |
    ForEach-Object {
        # If there is no file named MEDICAL*
        ## set the name of the new file to MEDICAL
        ## increase the count of the files named MEDICAL* of 1
        if (0 -eq $CountMedicalFiles) {
            $NewName = 'MEDICAL{0}' -f $_.Extension
            $CountMedicalFiles++    
        }
        # If there is at least 1 file named MEDICAL
        ## set the name of the new file to MEDICAL (N), where N depnds on the count of existing MEDICAL files
        else {
            # change this to set what number is the first you want between parenthesis.
            # -1 for (0), 0 for (1), 1 for (2) etc
            $BaseNumber = 0
            $NewName = 'MEDICAL ({0}){1}' -f ($BaseNumber + $CountMedicalFiles++), $_.Extension
        }
        # rename the file using the full path so it's certainly set in the same directory as the original file.
        Rename-Item -LiteralPath $_.FullName -NewName $NewName
        Write-Host ('Renamed {0} to {1}' -f $_.Name, $NewName)
    }

2 Comments

Good morning Sirtao. Thank you for your effort on this. Unfortunately it's not working at all. The file name is not completely "SF78" or "Medical", but these words are within the middle of the file name. I'm learning and reading what you've done and can most likely use some of these ideas in other places. The sample from "The Freelancer" is almost a success. Just need to fix the name part.
updated the answer. Check if it now fits your needs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.