我已经看到了一些与此类似的问题,但没有找到一个适合我情况的问题.
我有一个存储在文本文件中的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
Run Code Online (Sandbox Code Playgroud)
如果您希望脚本在第一次出错后退出循环,您可以尝试这样的方法:
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
}
}
Run Code Online (Sandbox Code Playgroud)
try..catch这里不需要AFAICS .
| 归档时间: |
|
| 查看次数: |
11099 次 |
| 最近记录: |