tambre tambre -4 years ago 345
PowerShell Question

PowerShell async download completion event handler never gets executed

I'm trying to create a PowerShell script that would download posh-git and then install it automatically. I'd like to have the download happen asynchronously, preferably with the option to have a callback once the download has finished and/or be able to wait for it to complete (but executing code until you want to wait).

I created a function that takes the URL for download, the path where to save it and the callback function. Unfortunately the callback function never seems to be called:

function DownloadFileAsync([string] $url, [string] $destination, [ScriptBlock] $action = $null)
$web_client = New-Object System.Net.WebClient

if ($action)
Register-ObjectEvent -InputObject $web_client -EventName DownloadFileCompleted -Action $action | Out-Null

$web_client.DownloadFileAsync($url, $destination)

$download_finished =
# This is never reached
echo "Download finished"

DownloadFileAsync "https://github.com/dahlbyk/posh-git/archive/master.zip" "C:/posh-git-master.zip" $download_finished

How can I fix the callback never being called? Is there also a way to implement a way to wait, later on in the code, for the download to complete?

Answer Source

Output from event action is not printed on PowerShell host, but captured and saved in job, returned by Register-ObjectEvent:

$web_client = New-Object System.Net.WebClient
$Job = Register-ObjectEvent -InputObject $web_client -EventName DownloadStringCompleted -Action {
    Write-Host 'Download completed'

Now when download completed, you can use Receive-Job $Job to receive job results.

If you want to print something on PowerShell host, then you need to use Write-Host or Out-Host cmdlets.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download