title: Rename a file if it exists powershell
body: <p>I have a script that will backup files from 100 days ago and will backup 5 days worth of files for the original backup. Then I will need to run the script everyday to backup any new files generated. I am trying to see if any file exists and if it does then rename it with a timestamp. I am not sure if I am going about this the right way. Is there anything I can do to make my script better?? Any help would be appreciated.</p>
  
  <pre><code>function BackupArtifacts {
  
  Param(
  $SourceFile,
  $Destination,
  $StartRange,
  $NumberOfDaysCopied
  )
  
  $NewFileName = $FileName_ + $TimeStamp
  
  New-Item -ItemType Directory -Force -Path $Destination
  $count = 0
  
  foreach ($fileList in Get-ChildItem $SourceFile -recurse) 
  {    
      if ($fileList.LastWriteTime -ge (Get-Date).AddDays($StartRange) -and $fileList.LastWriteTime -le (Get-Date).AddDays($StartRange + $NumberOfDaysCopied)) #Go back 100 days and copy 5 days worth of files
      { 
          #Check if file already exists and if it does then rename it 
          If (Test-Path ($Destination, $NewFileName) -join "")
          {
              While (Test-Path @($Destination, $NewFileName) -join "") 
              {
                  $NewFileName = "$NewFileName_ + $TimeStamp"
              }
              Rename-Item -Path ( ($Destination) -join '') -NewName ($NewFileName)
          }             
          try {
               #Copy-Item $fileList.FullName -Destination $Destination -Recurse
               Copy-Item -Path $SourceFile -Destination (@($Destination,$NewFileName) -join "") -Force
               Write-Host $fileList.FullName
               $count ++                                
          } catch {
          Write-Error $_
          }
       }                            
  }
  Write-Host "Backup complete, Number of files backed up:" $count
  }
  
  $SourceFile = "C:\TempCopy"
  $TimeStamp = Get-Date -f dd_MM_yyyy
  $Destination = "C:\TempCopyBackUp_" + $TimeStamp
  $StartRange = "-100"
  $NumberOfDaysCopied = "5"
  
  BackupArtifacts $SourceFile $Destination $StartRange $NumberOfDaysCopied
  </code></pre>