Search code examples
powershellautomationfilenameswebclientwebrequest

PowerShell DownloadFile for File name Changing every day


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.


Solution

  • $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/"