简体   繁体   中英

Download the latest file from URL

Really having a tough time with this one. We download a weekly file from a URL. I need to only download the newest file each week. I can't figure out how to grab the latest file. The file will always be WAYYYYMMDD.zip

$Url = "http://files.test.com/zips/weekly/WAYYYYMMDD.zip"
$Path = "C:\temp\WA2343.zip"
$Username = "*******"
$Password = "********"

$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)
$WebClient.DownloadFile( $url, $path )

Try this:

$CurrentDate = Get-Date -Format yyyyMMdd
$Url = "http://files.test.com/zips/weekly/WA$CurrentDate.zip"
$Path = "C:\temp\WA$CurrentDate.zip"
$Username = "*******"
$Password = "********"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)
$WebClient.DownloadFile( $url, $path )

Save the script and run it as a Windows scheduled task on the day of the week when the file is released.

the proposed solution should work but here is another version with some error handling:

$filename = 'WA{0}.zip' -f  (Get-Date -Format 'yyyyMMdd')
$uri = "http://files.test.com/zips/weekly/$filename"

try
{
    #This is to check if the URl exists or not
    Invoke-WebRequest -Uri $uri -Method Head -Verbose -ErrorAction Stop

    #if the above call succeeded without errors then download file
    Invoke-WebRequest -Uri $uri -OutFile (Join-Path C:\temp -ChildPath    $filename) -Credential (Get-Credential) -TimeoutSec 60
}
Catch
{
    Write-Warning ('Cant find the URL: {0}' -f $uri)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM