InvokeWebRequest - 在4XX / 5XX错误后继续读取文件

时间:2017-10-18 21:08:20

标签: powershell

我正在实施一种心跳,需要向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()
}

1 个答案:

答案 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
}