Invoke-WebRequest – Download files with PowerShell – Improved script!

A few months further I’ve learned and read some new things about Powershell and also about this Cmdlet. This resultated in an improved script compared to my old post Invoke-WebRequest. I just want to share it so maybe you can benefit from it too. The script now uses the Join-Path and Split-Path Cmdlets and a Leaf parameter. This results in more efficiënt code. I’ve also written a small feature which measures the time it took to download the file and also I’ve builtin some error handling because IF the download fails I don’t want to see the message ‘.NET Framework 4.6 download completed’ rather something like this ‘Something went wrong’. The PowerShell language is amazingly powerful!

$Uri = ""
$DownloadFileName = Split-Path $Uri -Leaf
$OutFile = Join-Path "$env:USERPROFILE" -ChildPath "Desktop"
$OutFile += "\$DownloadFileName"
$Timestamp = Get-Date
Invoke-WebRequest -Uri $Uri -OutFile $OutFile
Write-Host "Download completed. It took $((Get-Date).Subtract($Timestamp).Minutes) minutes and $((Get-Date).Subtract($Timestamp).Seconds) seconds ."
Write-Host "Something went wrong."

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s