Ralph
Ralph

Reputation: 1

How can I replace an entire file name using a CSV index in Powershell?

When the .mp3 files are downloaded from the call recording website they are not in our desired format. I want to replace the entire filename and move the files into a new folder. The default format is:

incoming#_outgoing#_yyyymmdd_hhmmss

I have a Search and Replace CSV which uses data from the call recording website:

Replace: Telephone call reference (TelCall_yyyymmdd_Surname)

Search: Exact call time from call recording software (yyyymmdd_hhmmss)

I have written a script that searches for the exact time and date in the filename and replaces it with the desired format:

    $folder = "C:\Users\R\Desktop\ClientCallsTest"
    $csv = "C:\Users\R\Desktop\20180104-0224_Client_Calls_PS_CSV.csv"

    $keywords = @{}
    Import-Csv $csv | ForEach-Object {
      $keywords[$_.Search] = $_.Replace
    }

    Get-ChildItem $folder -Recurse | ForEach-Object {
      $newname = $_.Name
      foreach ($word in $keywords.Keys) {
        $newname = $newname.Replace($word, $keywords[$word])
      }

      if ($_.Name -ne $newname) {
        Rename-Item -Path $_.FullName -NewName $newname
      }
    }

It indeed does rename the file, but only replaces the string in the CSV table. My desired format is just TelCall_yyyymmdd_Surname.

How would I modify this code to replace the entire file name (deleting the incoming/outgoing numbers at the beginning), rather than just the string in the lookup table? I'm sure it's a quick change but I'm stumped.

Upvotes: 0

Views: 77

Answers (1)

kim
kim

Reputation: 3421

You can use the string Split() function to split your original name into parts, like:

$nameParts = "incoming#_outgoing#_yyyymmdd_hhmmss" -split "_"

will give you an array like:

PS C:\>$nameParts
incoming#
outgoing#
yyyymmdd
hhmmss

you can then assemble your now string like:

$newName = "TelCal_" + $nameParts[2] + "_" + $surename

where $surename contains your data from the csv file

Upvotes: 1

Related Questions