2013-08-29 131 views
3

我已經看到類似這樣的幾個問題,但還沒有找到適用於我的情況的問題。檢查網址狀態的腳本

我有一個URL列表存儲在一個文本文件中,我需要運行以查看它們是否返回404錯誤。我正在使用powershell,並一直在使用這裏的例子:http://gallery.technet.microsoft.com/scriptcenter/Powershell-Script-for-13a551b3#content

我目前正在測試一個鏈接到一個合流頁面,看着Chrome中的控制檯我可以看到返回的第一個狀態是404 - Not Found,然後打了一打或之後的請求是304,200.

我猜在第一個404後,請求影響我的結果,我需要腳本返回基於第一個響應。

我已經嘗試過PowerShell,PHP和JavaScript解決方案,目前還沒有運氣。

總而言之,有一種方法可以根據第一個響應單獨返回答案嗎?

腳本:

## The URI list to test 
$URLListFile = "H:\xxx\xxx\urlList.txt" 
$URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue 
    $Result = @() 


    Foreach($Uri in $URLList) { 
    $time = try{ 
    $request = $null 
    ## Request the URI, and measure how long the response took. 
    $result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri } 
    $result1.TotalMilliseconds 
    } 
    catch 
    { 
    <# If the request generated an exception (i.e.: 500 server 
    error or 404 not found), we can pull the status code from the 
    Exception.Response property #> 
    $request = $_.Exception.Response 
    $time = -1 
    } 
    $result += [PSCustomObject] @{ 
    Time = Get-Date; 
    Uri = $uri; 
    StatusCode = [int] $request.StatusCode; 
    StatusDescription = $request.StatusDescription; 
    ResponseLength = $request.RawContentLength; 
    TimeTaken = $time; 
    } 

} 
    #Prepare email body in HTML format 
if($result -ne $null) 
{ 
    $Outputreport = "<HTML><TITLE>Website Availability Report</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Website Availability Report </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B></TD><TD><B>StatusCode</B></TD><TD><B>StatusDescription</B></TD><TD><B>ResponseLength</B></TD><TD><B>TimeTaken</B></TD</TR>" 
    Foreach($Entry in $Result) 
    { 
     if($Entry.StatusCode -ne "200") 
     { 
      $Outputreport += "<TR bgcolor=red>" 
     } 
     else 
     { 
      $Outputreport += "<TR>" 
     } 
     $Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>" 
    } 
    $Outputreport += "</Table></BODY></HTML>" 
} 

$Outputreport | out-file H:\xxx\xxx\test.htm 
Invoke-Expression H:\xxx\xxx\test.htm 
+0

你可以發佈你正在嘗試的PowerShell腳本嗎? – Mitul

+0

因此,您希望腳本在遇到一個錯誤時立即停止? –

回答

6

如果你希望你的腳本從第一個錯誤後循環退出,你可以嘗試這樣的事:

Foreach($Uri in $URLList) { 
    $error.Clear() 

    $time = Measure-Command { $request = Invoke-WebRequest -Uri $uri } 2>$null 

    if ($error.Count -eq 0) { 
    $time.TotalMilliseconds 
    } else { 
    $error[0].Exception.Response 
    break 
    } 
} 

AFAICS這裏不需要try..catch