title: Powershell Copy-Item Rename If File Exists
body: <p>I am using this code I found on this site in a script to copy PST files and rename the duplicate. My question and the problem I am having with it is that when it renames the .pst it continues to increment the number.</p>
  
  <p>For example, if it finds a file named "test.pst" it will copy it as is. If it finds another file also named "test.pst", it will copy it and rename it "test-1.pst" which is fine. However, if it finds two files named "test2.pst" it will copy the first one as "test2.pst" and copy and rename the second one to "test2-2.pst" instead of "test2-1.pst".</p>
  
  <p>Do you have any suggestions on how I can modify my code so that it will start numbering each new duplicate file with 1 (test3-1.pst, test4-1.pst, etc)?</p>
  
  <pre><code>$csv = import-csv .\test.csv
  foreach ($line in $csv) {
  New-Item c:\new-pst\$($line.username) -type directory
  
  $dest = "c:\new-pst\$($line.username)"
  $i=1
  
  Get-ChildItem -Path $line.path -Filter *.pst -Recurse | ForEach-Object {
  
  
      $nextName = Join-Path -Path $dest -ChildPath $_.name
  
      while(Test-Path -Path $nextName)
      {
         $nextName = Join-Path $dest ($_.BaseName + "_$i" + $_.Extension)
         $i++  
      }
  
      $_ | copy-Item -Destination $nextName -verbose
  }
  }
  </code></pre>