You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell脚本中实现URL与文件名联动的循环下载

解决PowerShell遍历URL与对应文件名批量下载的问题

你不需要用嵌套循环,因为你的$urlList和$fileList是一一对应的,直接按索引同时遍历两个集合就能实现URL和文件名的配对下载。以下是两种可行的实现方式:

方法1:使用索引循环

利用数组索引,同时获取对应位置的URL和文件名:

for ($i = 0; $i -lt $urlList.Count; $i++) {
    $currentUrl = $urlList[$i]
    $currentFile = $fileList[$i]
    Invoke-RestMethod -Uri $currentUrl -Headers @{Authorization = "Basic $base64AuthInfo"} -Method Get -OutFile $currentFile
}

方法2:使用Zip方法配对集合(PowerShell 5.1及以上版本支持)

把两个集合的元素配对成键值对,再遍历处理:

$urlFilePairs = $urlList | Zip $fileList -Name Url, FileName
foreach ($pair in $urlFilePairs) {
    Invoke-RestMethod -Uri $pair.Url -Headers @{Authorization = "Basic $base64AuthInfo"} -Method Get -OutFile $pair.FileName
}

修改后的完整脚本

把原来的循环替换成上面任意一种方法即可,完整脚本如下:

param (
    [Parameter (Mandatory = $false)]
    [object] $WebHookData
)
# Get all parameters from body 
# (passed from Data Factory Web Activity)
$Parameters = (ConvertFrom-Json -InputObject $WebhookData.RequestBody)
# Save Parameters for readability
# Check for ADF parameter. Not used when testing interactively
If ($Parameters.callBackUri)
{
    $callBackUri = $Parameters.callBackUri
}
# Demo parameter
$ParmMsg =  $Parameters.ParmMsg
# Main Script
Write-Output $ParmMsg
 
 
# If called from a webhook, use callBackUri to notify task is complete
If ($callBackUri)
{
    Invoke-WebRequest -Uri $callBackUri -Method Post
}

# set date for dynamic date field
#$date = Get-Date -UFormat "%Y-%m-%d"
$date = "2024-04-04"
$user = "username"
$pass = "password"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$pass)))
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$urlCollection = "https://url1/rest/ofscCore/v1/folders/dailyExtract/folders/" + $date + "/files/file1.xml","https://url2/rest/ofscCore/v1/folders/dailyExtract/folders/" + $date + "/files/file2.xml"
$separator = ","
$urlList = $urlCollection.Split($separator, $option)
$fileCollection = "file1.xml","file2.xml"
$fileList = $fileCollection.Split($separator, $option)

# 使用索引循环实现配对下载
for ($i = 0; $i -lt $urlList.Count; $i++) {
    $currentUrl = $urlList[$i]
    $currentFile = $fileList[$i]
    Write-Output "正在下载 $currentUrl 到 $currentFile"
    Invoke-RestMethod -Uri $currentUrl -Headers @{Authorization = "Basic $base64AuthInfo"} -Method Get -OutFile $currentFile
}

额外说明:你原来的$urlCollection和$fileCollection本身就是数组,不需要用Split方法拆分,直接用$urlList = $urlCollection和$fileList = $fileCollection就行,这样可以避免多余的拆分操作。

内容的提问来源于stack exchange,提问作者Jeremy Reynolds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:07:29