使用通配符使用Invoke-WebRequest下载文件

时间:2016-01-27 13:46:39

标签: powershell powershell-v3.0 powershell-ise

我有一个网址,其中有6位数字每天都在变化。

示例网站https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_160126.csv

这是更改的部分: 160126

我不知道正确的语法,但作为一种伪代码形式:

$url = "https://www.ecb.europa.eu/paym/coll/assets
/html/dla/ea_MID/ea_csv_" + [0-9][0-9][0-9][0-9][0-9][0-9]+ ".csv"

我该怎么写这个字符串?

要回答评论,我用它将该文件下载到一个文件夹,如下所示:

"https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_" + [0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9] +".csv"
$output = "C:\MyFolder\SomeSubFolder\ScriptDownload"
$start_time = Get-Date

Invoke-WebRequest -Uri $url -OutFile $output  
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"  

3 个答案:

答案 0 :(得分:2)

您可以通过下载页面或使用get-ElementById等来解析文件名的下载页面。 我假设,这是原始下载page

这是您的下载网址:

    $Url = "https://www.ecb.europa.eu/paym/coll/assets/html/list-MID.en.html"
$page = Invoke-WebRequest -Uri $Url
$a = ($page.ParsedHtml.getElementsByTagName('table') | ? {$_.classname -eq 'ecb-contentTable'}).textContent
$filename =  $a.Substring($a.IndexOf('ea_csv_'), 17)
$DLURL =  "https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/" + $filename

给出:

$DLURL
https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_160126.csv

用你的

完成
$output = "C:\MyFolder\SomeSubFolder\ScriptDownload\" + $filename
Invoke-WebRequest -Uri $DLURL -OutFile $Output

及其完成。

答案 1 :(得分:1)

6位数字是编码为YYMMDD的日期,对吗?如果是这样,您可以使用以下命令生成当天的URL:

$currentDay = $(get-date).ToString("yyMMdd")
$url = "https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_$currentDay.csv"

答案 2 :(得分:1)

你所要求的是无法做到的。然而,有更好,更可靠的方法来获得您正在寻找的相同结果。

我和Martin在一起。我也找到了他所做的下载页面。更好的方法是获取链接。现在这可能不是获取信息的最佳方式,但它是正确方向的开始。

请注意,这很慢。主要是因为Invoke-WebRequest

$start_time = Get-Date
$output = "C:\MyFolder\SomeSubFolder\ScriptDownload"
# Browse to the page hosting the csv file.
$request = Invoke-WebRequest "https://www.ecb.europa.eu/paym/coll/assets/html/list-MID.en.html"
# Locate the uncompressed CSV file name from the page
$filename = $request.ParsedHtml.getElementsByTagName("a") | Where-Object{$_.nameProp -match "^ea_csv_\d{6}\.csv$"} | Select -ExpandProperty nameProp
$fileurl = "https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/$filename"

# Get the file the is hosted today.
Invoke-WebRequest -Uri $fileurl -OutFile "$output\$filename" 
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"  

我们找到正确文件名的方式是使用^ea_csv_\d{6}\.csv$,其名称与“ea_csv_ [6位数] .csv”完全匹配。

相关问题