我的腳本中有以下代碼片斷,它使用WebRequest來ping一系列Web /應用程序服務器,並且我得到隨機結果,這些結果是根據好/壞服務器列在服務器列表。PowerShell的隨機WebRequest結果
例如,如果壞的服務器(我得到404或503的代碼)列在列表中的第一個,那麼我的腳本似乎準確報告。但是,如果優先服務器(返回狀態=「確定」)被首先列出,那麼我的結果是不準確的。
這裏是我的代碼片段:
$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.
爲什麼會出現不同的結果基礎上,服務器如何上市?
在此先感謝!
manojlds - 感謝您的反饋意見。非常有用,'$ response = $ null'完美運行! – Keith 2012-02-01 05:15:52