[Powershell] Copy and rename files as defined in a CSV mapping file

Ha! What a title. I have no idea how else to describe it.

This is really a Part 2 to my earlier blog post, Powershell: Create files in a directory from a CSV list

In that post, I created a massive list of documents. Now the script I really needed was to rename them based on a mapping in a CSV document.

Brief:

  • Copy a file from one directory to another, renaming them based on a mapping CSV document;
  • Actions get logged;
  • Check file exists before copying, log then skip
  • Log if the file is being overwritten or not

CSV File Headers

SourceID,DestinationID

The Powershell Code:

$mappinglist = ".\mapping.csv"
$sourcedocs = "\path\to\source\folder"
$destdocs = "\path\to\destination\folder"
$date = get-date -format yyyyMMddHHmm
$logfile = ".\$date-documentcopy.log"

Add-Content $logfile "### $date Starting Document Copying ###"
Import-Csv $mappinglist | Foreach-Object { 
  $srcfile = $_.SourceFile ;
  $destfile= $_.DestinationFile;

  If (!(Test-Path $destdocs\$destfile)) {
    Add-Content $logfile "$srcfile ($destfile) not found in destination directory"
    Write-Host "$srcfile ($destfile) not found in destination directory"
  }
  if (Test-Path $sourcedocs\$srcfile) {
    Write-Host "$srcfile copying to $destdocs\$destfile"
    Copy-Item $sourcedocs\$srcfile $destdocs\$destfile"
    Add-Content $logfile "$srcfile copied to $destdocs\$destfile"
  } else {
    Write-Host "$srcfile source document not found ... skipping"
    Add-Content $logfile "$srcfile source document not found ... skipping"
  }
}
Add-Content $logfile "### $date Finished Document Copying  ###"

Notes:
Most of the code is done in a few lines, however for my purpose, I really needed to have everything logged as we generate formal reports on basically everything we do!
I’m a big fan of timestamping my log files, hence the $date-documentcopy.log line.
Also, I like being able to see what’s going AND having it log to file, so I duplicate the Add-Content and the Write-Host lines.
I rather like the Write-Host “copying” and Add-Content “copied” line. The reason for this is I have some large files (>2GB) so *if* it fails I can see on-screen which record it was but the log has it once it’s finished.

Leave a Reply

Your email address will not be published. Required fields are marked *