Jonathan Singer
Jonathan Singer

Reputation: 11

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.

Upvotes: 1

Views: 200

Answers (2)

mklement0
mklement0

Reputation: 437042

With hundreds of CSV rows, it pays to build up a hashtable up front that maps old names to new names.

You then only need to loop once over the file names, performing a fast hashtable lookup in each iteration.

# Initialize the hashtable.
$ht = @{}

# Fill the hashtable, with the "name" column's values as the keys,
# and the "newname" columns as the values.
Import-Csv C:\TEST\Book1.csv | 
  ForEach-Object {
    $ht.Add($_.name, $_.newname)
  }


# Loop over the files and rename them based on the hashtable
Get-ChildItem C:\TEST\*.DOCX | Rename-Item -NewName {
  $prefix = ($_.BaseName -split '_')[0] # Get prefix (before "_")
  $newPrefix = $ht[$prefix] # Look up the prefix in the hashtable.
  if ($newPrefix) { # Replace the prefix, if a match was found.
    $newPrefix + $_.Name.Substring($prefix.Length)
  }
  else { # No replacement - output the original name, which is a no-op.
    $_.Name 
  }
} -WhatIf

-WhatIf previews the renaming operations; remove it to perform actual renaming.

Upvotes: 0

jfrmilner
jfrmilner

Reputation: 1768

Give this a try, remove the WhatIf if it works for your files. Else, we'll need to see some sample data from the csv.

foreach ($item in $CSV) {
    foreach ($file in $files) {
        if ($item.name -eq $file.basename) {
            Rename-Item $file.fullname -NewName $($file.FullName -replace $item.name, $item.newname) -WhatIf
        }
    }
}

Upvotes: 1

Related Questions