title: How do I most efficiently move, rename files and log this action?
body: <p>I have the following CSV list (in reality 1000s of lines):</p>
  
  <pre>needle,code
  123456,AB
  121212,BB
  33333333,CVV</pre>
  
  <p>And I have a directory (<code>C:\old_files</code>) containing PDF files (again, 1000s in reality):</p>
  
  <pre>dsadsadsa.343222.dsads23213jkjl.saddsa.pdf
  dsadsadsa.123456.dsads23213jkjl.saddsa.pdf
  dsadsadsa.111111.dsads23213jkjl.saddsa.pdf
  dsadsadsa.33333333.dsads23213jkjl.saddsa.pdf
  dsadsadsa.33333333.fsdgdsfdsfdsf.dsad.pdf</pre>
  
  <p>For each needle in the CSV:</p>
  
  <ul>
  <li>I have to see if there is a PDF containing that needle (there might be 0 or more matches)</li>
  <li>If there is a match, I have to
  
  <ol>
  <li>make a copy of the file into a separate folder (<code>D:\new_files</code>)</li>
  <li>rename the copied file by prepending the respective code to the name</li>
  <li>write an entry into the log.</li>
  </ol></li>
  </ul>
  
  <p>For the example, I have a match for <code>123456</code> and 2 for <code>33333333</code>, so I have to move a copy of these files into <code>D:\new_files</code> and rename them into:</p>
  
  <pre>AB.dsadsadsa.123456.dsads23213jkjl.saddsa.pdf
  CVV.dsadsadsa.33333333.dsads23213jkjl.saddsa.pdf
  CVV.dsadsadsa.33333333.fsdgdsfdsfdsf.dsad.pdf</pre>
  
  <p>The logfile would look like (format <code>needle,code,oldfilepath,newfilepath</code>):</p>
  
  <pre>123456,AB,C:\old_files\dsadsadsa.123456.dsads23213jkjl.saddsa.pdf,D:\new_files\AB.dsadsadsa.123456.dsads23213jkjl.saddsa.pdf
  33333333,CVV,C:\old_files\dsadsadsa.33333333.dsads23213jkjl.saddsa.pdf,D:\new_files\CVV.dsadsadsa.33333333.dsads23213jkjl.saddsa.pdf
  33333333,CVV,C:\old_files\dsadsadsa.33333333.fsdgdsfdsfdsf.dsad.pdf,D:\new_files\CVV.dsadsadsa.33333333.fsdgdsfdsfdsf.dsad.pdf</pre>
  
  <p>It is important that I only loop over the files in the directory once, because iterating through all files in a <code>ForEach</code> loop for each <code>needle</code> takes way too long. So with thanks to this forum I'm building a hashtable first:</p>
  
  <pre><code>$pairs = @{}
  Import-CSV .\data.csv | ForEach-Object { $pairs[$_.needle] = $_.code+"." }
  
  Get-ChildItem "C:\old_files" | Rename-Item -NewName { "D:\new_files\" + $pairs[$_.Name.Split('.')[1]] + $_.Name }
  </code></pre>
  
  <p>My first problem here: I am unable to move the file into the new folder.</p>
  
  <p><strong>Q1</strong> How do I properly copy a file from <code>C:\old_files</code> into <code>D:\new_files</code> and rename it?</p>
  
  <p>My second problem: I don't understand how I can add code to the above code.</p>
  
  <p><strong>Q2</strong> How can I create the logfile for each match (and therefore: copied and renamed file)?</p>