Download file from HTTP request using PowerShell

Download file from HTTP request using PowerShell

No comments

 7,930 total views,  8 views today

Many times, due to the business requirement we might need to download a file from an external link through the HTTP or HTTPS API call. In this blog, we will learn about how to download a file from an HTTP request using PowerShell script. Before getting into the script we must little know about Invoke-WebRequest.

What is Invoke-WebRequest in PowerShell HTTP call?

In simple, using the Invoke-WebRequest PowerShell command we can download a file from an external link in a specific location.

How does Invoke-WebRequest command work in PowerShell?

The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page, web service, or Web API. It parses the response and returns collections of links or a single link (based on the request was being sent), images, and other HTML elements.

This cmdlet was introduced in PowerShell 3.0.

Beginning in PowerShell 7.0, Invoke-WebRequest supports proxy configuration defined by environment variables.

Example:


$Response = Invoke-WebRequest -URI https://www.bing.com/search?q=how+many+feet+in+a+mile
$Response.InputFields | Where-Object {
$_.name -like "* Value*"
} | Select-Object Name, Value

name value
---- -----
From  Value  1
To    Value  5280

The above uses the Invoke-WebRequest cmdlet to send a web request to the Bing.com site.


#################PowerShell script to download file from an external link#####################################

cls

$fileName = "Download_File_Report"
#'yyyyMMddhhmm yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"
$invocation = (Get-Variable MyInvocation).Value
$directoryPath = Split-Path $invocation.MyCommand.Path

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))
{
New-Item -ItemType directory -Path $directoryPathForLog
#Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
#$logPath = $directoryPath + "\" + $logFileName

$logPath = $directoryPathForLog + "\" + $logFileName

$isLogFileCreated = $False
function Write-Log([string]$logMsg)
{
if(!$isLogFileCreated){
Write-Host "Creating Log File..."
if(!(Test-Path -path $directoryPath))
{
Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
else
{
$script:isLogFileCreated = $True
Write-Host "Log File ($logFileName) Created..."
[string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
Add-Content -Path $logPath -Value $logMessage
}
}
else
{
[string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
Add-Content -Path $logPath -Value $logMessage
}
}
try
{

$folderWhereToDownload = "C:\temp"
$externalFileURL= "https://ExternalLinkURLToDownload/fileName123.xlsx"
$request = [System.Net.HttpWebRequest]::Create($externalFileURL)
$request.Method = "HEAD"
$response = $request.GetResponse()
$fUri = $response.ResponseUri
$fileName = [System.IO.Path]::GetFileName($fUri.LocalPath);
$response.Close()
$targetLocation = join-path $folderWhereToDownload $filename
Invoke-WebRequest -Uri $externalFileURL -OutFile $targetLocation
Write-Host "The file successfully has been downloaded" -ForegroundColor Green

}

Catch
{
$ErrorMessage = $_.Exception.Message +"in downloading file from an external link!:"
Write-Host $ErrorMessage -BackgroundColor Red
Write-Log $ErrorMessage

}

#################PowerShell script to download file from an external link - ends here##########################

How to use the above script?

Just, we need to replace the below variables:


$folderWhereToDownload = "Local drive location to download the file" #Example: "C:\temp"
$externalFileURL= "Here we need to pass the external file URL" #Example : "https://ExternalLinkURLToDownload/fileName123.xlsx"

Reference:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7#:~:text=%5B%5D-,Description,was%20introduced%20in%20PowerShell%203.0.

Summary

Thus in this blog, we have learned how to download a file from a HTTP external URL using the PowerShell script.

See Also

You may also like the following SharePoint PowerShell tutorials:

Free download SharePoint Online & Office 365 Administration eBook(238 Pages)

Get the PDF eBook from here:


 
FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.