从URL下载最新文件

时间:2015-06-29 02:03:55

标签: powershell

真的很难用这个。我们从URL下载每周文件。我只需要每周下载最新的文件。我无法弄清楚如何获取最新文件。该文件将始终为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 )

2 个答案:

答案 0 :(得分:1)

试试这个:

$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 )

保存脚本并在文件发布的一周中将其作为Windows计划任务运行。

答案 1 :(得分:0)

建议的解决方案应该有效,但这是另一个带有错误处理的版本:

$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)
}