关于powershell:使用”Invoke-WebRequest”下载多个文件 | 珊瑚贝

downloading multiple files with “Invoke-WebRequest”


所以我刚刚开始使用 powershell,我正在尝试找到一种通过 Invoke-WebRequest 传递数组的方法,以便我可以下载多个文件。我意识到它只能处理字符串,所以这就是我想出的。

1
2
3
$urls = Get-Content .\\urls.txt
$outputs = Get-Content .\\outputs.txt
foreach ($url in $urls) {foreach ($output in $outputs){InvokeWebRequest Uri $url OutFile $output}}

现在,这个片段可以工作了,但是由于我已经嵌套了两个 foreach\\’es,它会下载内容两次。

我希望它与现在做的一样,但没有”双重下载”。

感谢我能得到的任何帮助。


只是为了发布 Charlie\\’s answer 的替代方案,您还可以使用哈希表来创建 URL\\’s 和输出目录之间的关联。这将防止您在修改任一 .txt 文件时出现意外结果。在实践中,它与 CSV 解决方案非常相似,但是哈希表可以在脚本中维护或根据两个文本文件的内容(一个文件中的所有键和另一个文件中的所有值)生成。

1
2
3
4
5
6
7
8
$myHash = @{
    ‘www.url1.com/file.log’ = ‘c:\\temp\\output1.log’;
    ‘www.url2.com/file.log’ = ‘d:\\myotherdrive\\output.log’;
}

ForEach ($file in $myHash.GetEnumerator()) {
    InvokeWebRequest Uri $file.Key OutFile $file.Value
}


现有答案提出了重组输入数据的合理替代方案,以便在 URL 和输出文件之间建立单源映射,但要回答所提出的问题:

1
2
3
4
5
6
$urls = Get-Content .\\urls.txt
$outputs = Get-Content .\\outputs.txt

foreach ($i in 0..($urls.Count1)) {
  InvokeWebRequest Uri $urls[$i] OutFile $outputs[$i]
}

0..($urls.Count-1) 创建一个与数组 $urls 的元素相对应的索引数组,foreach 使用迭代变量 $i 循环,然后用于访问 $urls 和 < 的配对数组元素x5>.

假设,索引数组的创建在内存使用方面的元素计数非常高时可能会出现问题;如果这是一个问题,请注意 PowerShell 还支持类似 C# 的 for 语句,它更节省内存,但速度较慢:

1
for ($i = 0; $i -lt $urls.count; ++$i) {

您可以使用所需的 URL 和输出之间的映射创建一个 CSV,然后循环遍历它:

1
2
3
4
5
$csvData = Import-Csv url-andoutputs.csv

foreach($row in $csvData){
    InvokeWebRequest Uri $row.url OutFile $row.output
}

您的 CSV 文件需要顶行作为列名,即 “url” 和 “output”

  • 非常感谢,这正是我需要的,保重!


来源:https://www.codenong.com/50883889/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9957.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?