Rename Part of File Name

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 = Import-Csv “C:\TEST\Book1.csv”

# location of your files
$files
= get-childitem “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.

 

 

 

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

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?