我正在实施一种心跳,需要向URL列表发送GET请求。
我正在从.txt读取URL,如果HTTP状态代码不是200,InvokeWebRequest会导致我的脚本终止。如何解决此问题,以便我的脚本继续读取/处理文件中的其余行?
已经尝试过-ErrorAction ContinueSilently
$reader = [System.IO.File]::OpenText($filePath)
Try {
while ($null -ne ($line = $reader.ReadLine())) {
Write-Host -foregroundcolor "YELLOW" "Processing URL: $line"
Invoke-WebRequest -Method GET -Uri $line -DisableKeepAlive -TimeoutSec 5 | Select-Object StatusCode,StatusDescription | Format-List
}
}
Catch {
$exceptionString = $_.Exception.ToString()
If($exceptionString -match '404') { Write-Host "FCK" }
}
Finally {
$reader.Close()
}
答案 0 :(得分:2)
You could either move the try/catch block to include only the call to the web service method OR add another try/catch block within the current one, but again, just for the line that calls the web service method.
For example,
try
{
Invoke-WebRequest -Method GET -Uri $line -DisableKeepAlive -TimeoutSec 5 | Select-Object StatusCode,StatusDescription | Format-List
}
catch
{
# could output specific or general error message, but otherwise ignore
}