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?