Copying Files in the Background

by Jun 4, 2012

In a previous tip we showed how you can use the BITS service to copy files. The main advantage of BITS is that it can copy things silently in the background, and it is resilient to interruptions such as reboots. After a reboot, BITS will continue the copy process, so this can be a good starting point to create a robust backup mechanism.

Import-Module BitsTransfer

# adjust source and destination to your needs:
$Source = "$env:userprofile\downloads\*.exe"
$Destination = "C:\BackupFolder\"

if ( (Test-Path $Destination) -eq $false) 
{
    $null = New-Item -Path $Destination -ItemType Directory 
}

$params = @{
    Source = $Source 
    Destination = $Destination 
    Description = "Backup" 
    DisplayName = "Backup" 
    Asynchronous = $true
}

Start-BitsTransfer @params 

This script would copy all downloaded EXE files to a backup location. Since the backup is running in the background, you get back immediately a response.

To check progress, you can check progress using Get-BITSTransfer. You can call this cmdlet anytime, even next week after a couple of restarts. It may look like this:

PS> Get-BitsTransfer

You may see other BITS operations in this list as well since Windows is using the BITS service, too, to receive updates and upload data.

To actually complete the backup once it is done, you need to call Complete-BITSTransfer:

Import-Module BITSTransfer

Get-BitsTransfer |
  Where-Object { $_.DisplayName -eq 'Backup' } |
  ForEach-Object {
    $_ | Select-Object -Property *

    if ($_.JobState -eq 'Transferring') {
      $transferred = $_.FilesTransferred
      $total = $_.FilesTotal
      $text = '{0} of {1} files transferred. Try again later.' -f $transferred, $total
      Write-Warning $text
    } else {
      $done = $_.TransferCompletionTime
      Complete-BitsTransfer $_
      Write-Warning "Backup process done at $done"
    }
  }

Twitter This Tip! ReTweet this Tip!