首页 > 解决方案 > For-each 循环无法处理所有字符串

问题描述

我正在尝试使用一堆字符串和一个锚 URL 生成 URL

s.txt 中的字符串是

123

234

345

锚点 URL 是https://testurl.com/prod/hostdetails.php?qs=

我正在使用的代码

$ur = gc C:\temp\s.txt
foreach($u in $ur) {
$test = invoke-webrequest -uri "https://testurl.com/prod/hostdetails.php?qs=$u"  -UseDefaultCredentials
}
$test

但它仅返回数据

https://testurl.com/prod/hostdetails.php?qs=345

标签: powershellloops

解决方案


这是因为您在循环中每次都重新分配。 $test我建议这个解决方案:

$test = 'https://testurl.com/prod/hostdetails.php?{0}' -f ((C:\temp\s.txt) -join '&')

您编辑了您的问题。这可能是您正在寻找的。请注意+=运算符连接结果:

$result = @()
Get-Content C:\temp\s.txt | ForEach-Object {
    $result += invoke-webrequest -uri "https://testurl.com/prod/hostdetails.php?qs=$($_)"
}

推荐阅读