【发布时间】:2012-02-01 04:34:26
【问题描述】:
我的脚本中有以下 sn-p,它使用 WebRequest 来 ping Web/应用服务器列表,并且我根据服务器列表中列出的好/坏服务器的顺序获得随机结果。
例如,如果坏服务器(我得到的代码为 404 或 503)列在列表的首位,那么我的脚本似乎报告准确。但是,如果首先列出了好的服务器(返回状态 =“OK”),那么我的结果是不准确的。
这是我的代码 sn-p:
$ServerList = gc "$pwd\servers\test_servers.lst"
ForEach ($_ in $ServerList)
{
# Ping web server test
$url = "http://$_.domain.net/logon"
Write-Host "Pinging web address for server: $url ..."
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
If ($response.StatusCode -eq "OK")
{
#$True
Write-Host "Web Ping on $_ Succeeded."
}
Else
{
#$False
Write-Host "Web Ping on $_ FAILED!!!"
}
}
这是示例服务器列表:
server1 (reports back a 404)
server2 (reports back a 503)
server3 (gets a status = "OK")
这是我运行脚本时“准确”的 cmd 输出:
C:\TFS\Sandbox>powershell ./temp.ps1
Pinging web address for server: http://server1.domain.net/wfc/logon ...
Exception calling "GetResponse" with "0" argument(s): "The remote server return
ed an error: (404) Not Found."
At C:\TFS\Sandbox\temp.ps1:8 char:34
+ $response = $request.GetResponse <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Web Ping on server1 FAILED!!!
Pinging web address for server: http://server2.domain.net/wfc/logon ...
Exception calling "GetResponse" with "0" argument(s): "The remote server return
ed an error: (503) Server Unavailable."
At C:\TFS\Sandbox\temp.ps1:8 char:34
+ $response = $request.GetResponse <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Web Ping on server2 FAILED!!!
Pinging web address for server: http://server3.domain.net/wfc/logon ...
Web Ping on server3 Succeeded.
现在,当我重新排序服务器列表时,首先列出了好服务器,如下所示:
server3 (gets a status = "OK")
server1 (reports back a 404)
server2 (reports back a 503)
我得到不准确的结果,服务器 1 和服务器 2 被报告为正常:
Pinging web address for server: http://server3.domain.net/wfc/logon ...
Web Ping on server3 Succeeded.
Pinging web address for server: http://server1.domain.net/wfc/logon ...
Exception calling "GetResponse" with "0" argument(s): "The remote server return
ed an error: (404) Not Found."
At C:\TFS\Sandbox\temp.ps1:8 char:34
+ $response = $request.GetResponse <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Web Ping on server1 Succeeded.
Pinging web address for server: http://server2.domain.net/wfc/logon ...
Exception calling "GetResponse" with "0" argument(s): "The remote server return
ed an error: (503) Server Unavailable."
At C:\TFS\Sandbox\temp.ps1:8 char:34
+ $response = $request.GetResponse <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Web Ping on server2 Succeeded.
为什么我会根据服务器的列出方式得到不同的结果?
提前致谢!
【问题讨论】:
标签: powershell webrequest