2017-10-18 47 views
0

我正在實施一種心跳,需要向URL列表發送GET請求。InvokeWebRequest - 在4XX/5XX錯誤後繼續讀取文件

我從.txt閱讀網址,InvokeWebRequest使我的腳本終止如果HTTP狀態代碼不是200我如何去解決這個所以我的腳本繼續讀/處理文件中剩餘的行?

已經嘗試過-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() 
} 

回答

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 
} 
+0

謝謝!清除我在Try塊中的混亂是解決方案。 – DMS