Rename Part of File Name

Welcome Forums General PowerShell Q&A Rename Part of File Name

This topic contains 2 replies, has 3 voices, and was last updated by

 
Participant
2 weeks, 6 days ago.

  • Author
    Posts
  • #180369

    Participant
    Topics: 1
    Replies: 0
    Points: -7
    Rank: Member

    I am looking to batch rename part of a pdf file using a csv file. I have a csv file with two columns, name and Newname. My pdf files have a naming convention of 222222_test (for example) and are located in the C:\TEST folder. In the csv file, 222222 is in the name column and Jonathan is in the Newname column.
    The folder is really going to have hundreds of pdf documents whenever I can get this to work.

    $csv    = ImportCsv "C:\TEST\Book1.csv"

    # location of your files
    $files
    = getchilditem "C:\TEST\*.DOCX"

    foreach($item in $CSV){
    foreach
    ($file in $files){
    if($item.name eq $file.basename){
    rename
    item $file.fullname NewName         "$($item.newname)$($file.extension)" Verbose
    }
    }
    }

     

    I am looking for a way for the 222222 (only) to be changed to Jonathan so the pdf file would be Jonathan_test. I was able to use the code when the file name is only 222222 but when the pdf is 222222_test, the code is not working.

     

     

     

  • #180408

    Participant
    Topics: 1
    Replies: 96
    Points: 514
    Helping Hand
    Rank: Major Contributor

    You can use -match operator instead of -eq in the if statement.

  • #180438

    Participant
    Topics: 1
    Replies: 1552
    Points: 2,700
    Helping Hand
    Rank: Community Hero

    Something like this could work ...

    $csv = Import–Csv "C:\TEST\Book1.csv"
    $files = get–childitem "C:\TEST\*.DOCX"
    
    foreach ($item in $CSV) {
        foreach ($file in $files) {
            if ($file.basename –match $item.name) {
                $NewName = $file.name -replace "$Item.name","$Item.NewName"
                Rename-Item -Path $file.fullname -NewName $NewName -WhatIf
            }
        }
    }

    Shouldn't you looking for *.pdf files in your Get-ChildItem?

You must be logged in to reply to this topic.