我有以下代码片段,脚本使用 WebRequest 对一组网站/应用服务器进行 ping 测试,但依赖于服务器列表中的好坏服务器的顺序,结果会出现随机性。
例如,如果先列出404或503的不良服务器,则脚本的报告似乎是准确的。然而,如果首先列出状态为“OK”的好服务器,则结果不准确。
以下是我的代码片段:
这是一个服务器列表示例:
现在如果我重新排列服务器列表,将好的服务器放在第一位,像这样:
为什么服务器列表不同会导致结果不一致?
谢谢!
例如,如果先列出404或503的不良服务器,则脚本的报告似乎是准确的。然而,如果首先列出状态为“OK”的好服务器,则结果不准确。
以下是我的代码片段:
$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")
当我运行脚本时,以下是“准确”的命令行输出:
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.
为什么服务器列表不同会导致结果不一致?
谢谢!
Remove-Variable
,以防它在赋值时没有被清空。 - Andy Arismendi