PowerShell DownloadFile for File name Changing every day

Viewed 48

Code below to download a file from website: https://www.mcafee.com/enterprise/en-us/downloads/security-updates.html

File being downloaded

However, the file name is changing every day. For example: 'mediumepo4981dat.zip' today and 'mediumepo4980dat.zip' yesterday.

How can I create a script which I can run daily which works dynamically?

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$uri = "https://download.nai.com/products/datfiles/med/mediumepo4981dat.zip"
$filename = "C:\DownloadTest\mediumepo4981dat.zip"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$wc.DownloadFile($uri, $filename)

Please let me know if you need any further clarification.

Note: Looking for a solution without Invoke-WebRequest as that does not work in my current environment.

2 Answers

Seems like we can assume that the last file listed is always the newest, can't confirm if this will always be true it may change at some point. For the time being, this is how you can get the last file:

$uri  = [uri] "https://download.nai.com/products/datfiles/med"
$wr   = Invoke-WebRequest $uri
$file = $wr.ParsedHtml.getElementsByTagName('a') |
    Select-Object -Last 1 -ExpandProperty TextContent
$toDownload = [uri]::new($uri, $file)

Now you can combine this with the rest of your script:

$filename = Join-Path 'C:\DownloadTest\' -ChildPath $file
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$wc.DownloadFile($toDownload.AbsoluteUri, $filename)

Note that this will work only in Windows PowerShell.

$uri  = [uri] "https://download.nai.com/products/datfiles/med"
$wr   = Invoke-WebRequest $uri
$file = $wr.ParsedHtml.getElementsByTagName('a') |
    Select-Object -Last 1 -ExpandProperty TextContent
$toDownload = [uri]::new($uri, $file)

is missing trailing '/' in $uri. It should be

  $uri  = [uri] "https://download.nai.com/products/datfiles/med/"
Related