2013-09-01 25 views
0

我在SCOM PowerShell脚本中使用Invoke-WebRequest来定期监视URI的可用性。我的脚本是相当简单的(因为我有PS :-)不甚了解):Invoke-WebRequest在服务器无法访问后工作

$scomapi = new-object -comObject "MOM.ScriptAPI" 
$scompb = $scomapi.CreatePropertyBag() 
$fullHostName = "https://" + <full path to monitored web endpoint> 
$result = Invoke-WebRequest $fullHostName 
if($result.content) { 
    $scompb.AddValue("ConfigurationReachable",$true); 
} else { 
    $scompb.AddValue("ConfigurationReachable",$false); 
}   
$scomapi.AddItem($scompb) 
$scomapi.ReturnItems() 

为了测试这个剧本,我没有运行SCOM代理,我在客户端上手动更改在hosts文件想要做的监测。有趣的是,即使在主机无法访问的情况下,该脚本也可以成功获取Web端点(通过从该机器执行ping操作进行测试)。

我直接从命令行做了一些进一步的测试,没有任何改变。即使我没有ping到远程地址,Invoke-WebRequest仍会成功并获取网页。那么我在这里做错了什么?

回答

1

没有测试它,我猜它是DNS缓存。

powershell会话可能会缓存第一个请求的IP,并忽略您的主机文件更新(只使用旧的工作IP)。

尝试在断开网络适配器/电缆以模拟服务器故障之前和之后运行脚本。

UPDATE:我想要上面说的是,该脚本将完美地工作,如果服务器不可用,但使用的主机文件你的模拟给人一种“假阳性”(所以忽略结果)。

[System.Net.ServicePointManager]::DnsRefreshTimeout = 0 
+0

我在虚拟机上运行,​​但无法访问虚拟机管理程序(我可以访问但需要一些时间)。任何想法如何清除PowerShell会话?有没有一些选项可以清除它,或者使用另一个不使用缓存的命令? – vainolo

+0

查看更新的答案 –

+0

奇怪...不起作用。我也尝试执行'Clear-DnsClientCache',但没有任何反应。不管怎么说,还是要谢谢你。 – vainolo

2

每讨论的意见:

如果你真的需要编辑hosts文件来测试脚本,加入下面一行在你的脚本开始禁止在会议上的.Net DNS缓存问题在于缓存;只有它不是被缓存的IP才是问题(至少,不是唯一的问题);内容也被缓存;所以不要去网络服务器来获取资源,系统的作弊和获取本地资源。 您可以通过将-Headers @{"Cache-Control"="no-cache"}添加到您的invoke-webrequest来防止此问题。

查看下面的示例测试脚本;在hosts文件调整之前和之后,尝试使用和不使用cache-control标题。

cls 

$urlHost = 'server.mydomain.com' 
$endpointUrl = ("https://{0}/path/to/resource.jpg" -f $urlHost) 

#can be set once at the start of the script 
[System.Net.ServicePointManager]::DnsRefreshTimeout = 0 

#I don't have Clear-DnsClientCache; but the below should do the same thing 
#Should be called inside any loop before the invoke-webrequest to ensure 
#flush your machine's local dns cache each time 
ipconfig /flushdns 

#prove that our hosts update worked: 
#optional, but will help in debugging 
Test-Connection $urlHost -Count 1 | select ipv4address 

#ensure we don't have a remembered result if invoke-request is in a loop 
$result = $null 
#make the actual call 
#NB: -headers parameter takes a value telling the system not to get anything 
#from the cache, but rather to send the request back to the root source. 
$result = Invoke-WebRequest $endpointUrl -Headers @{"Cache-Control"="no-cache"} 

#output the result; 200 means all's good (google http status codes for info on other values) 
("`nHTTP Status Code: {0}`n" -f $result.StatusCode) 

#output actual result; optional, but may be useful to see what's being returned (e.g. is it your page/image, or a 404 page/something unexpected 
$result 
0

我知道这是旧的,但万一这可以帮助别人:

我跑过一个类似的问题,并添加“ - 禁用保持活动”解决对我来说。