How to run script on BITS download completion

bits-service, microsoft-bits, powershell

Solution

I would suggest using the BitsTransfer module as it exposes native PowerShell methods for working with BITS jobs. To get started, you simply instruct PowerShell to load the BITS module:

Import-Module BitsTransfer

Running Get-Command to see what new BITS cmdlets have been added shows:

PS C:\> Get-Command  *-bits*

CommandType     Name
-----------     ----
Cmdlet          Add-BitsFile
Cmdlet          Complete-BitsTransfer
Cmdlet          Get-BitsTransfer
Cmdlet          Remove-BitsTransfer
Cmdlet          Resume-BitsTransfer
Cmdlet          Set-BitsTransfer
Cmdlet          Start-BitsTransfer
Cmdlet          Suspend-BitsTransfer

The one you will most likely be interested in would be Start-BitsTransfer:

Start-BitsTransfer -Source http://localhost/BigInstaller.msi

The cmdlet will show a progress bar on the screen and wait for the download to finish - the next command in your script won't execute until the download has finished.

For async tasks, you can add the `-Asynchronous` parameter to the Start-BitsTransfer cmdlet, which will queue up the download and let it run in the background. You can manage those downloads with the Get-BitsTransfer and Complete-BitsTransfer cmdlets.

PS C:\> Start-BitsTransfer -Source http://localhost/BigInstaller.msi -Async
JobId                   DisplayName    TransferType  JobState
-----                   -----------    ------------  --------
da7bab7f-fbfd-432d-8... BITS Transfer  Download      Connecting

PS C:\> Get-BitsTransfer
JobId                   DisplayName    TransferType  JobState
-----                   -----------    ------------  --------
da7bab7f-fbfd-432d-8... BITS Transfer  Download      Transferred

# finish and jobs that have transferred (e.g. write them to destination on disk)
PS C:\> Get-BitsTransfer | ? {$_.JobState -eq "Transferred"} | Complete-BitsTransfer

Problem

I am trying to automate the download and installation of a large application that is several hundreds of MB to a few GB in size. I am looking into using BITS and powershell to asynchronously download the application and then launch the setup. Using the deprecated `bitsadmin` command there is a `/SETNOTIFYCMDLINE`option that would allow me to chain the execution of the setup once the download completes. How can I perform this with powershell? This will be my first powershell script, so if you have any links to examples that would be great. Thanks

Original source