1

Invoke-WebRequest在 SCOM PowerShell 脚本中使用定期监视 URI 的可用性。我的脚本相当简单(因为我对 PS 知之甚少 :-)):

$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()

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

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

4

3 回答 3

5

根据评论中的讨论,问题正在缓存;只是问题不是被缓存的IP(至少,不是唯一的问题);内容也被缓存;所以不是去网络服务器来获取你的资源,而是系统作弊并在本地获取它。您可以通过添加-Headers @{"Cache-Control"="no-cache"}到您的invoke-webrequest.

请参阅下面的示例测试脚本;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
于 2015-06-11T18:06:04.317 回答
5

我知道这是旧的,但以防万一这有助于某人:

我遇到了类似的问题,添加“-Disable KeepAlive”为我解决了这个问题。

于 2017-04-11T20:21:16.077 回答
1

如果不对其进行测试,我猜它是 dns 缓存。

powershell-session 可能会在第一个请求时缓存 ip 并忽略您的主机文件更新(仅使用旧的工作 ip)。

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

更新:我上面想说的是,如果服务器不可用,脚本将完美运行,但您使用主机文件的模拟给出了“误报”(因此忽略结果)。

如果您确实需要通过编辑主机文件来测试脚本,请通过在脚本开头添加以下行来禁用会话中的 .Net dns 缓存:

[System.Net.ServicePointManager]::DnsRefreshTimeout = 0
于 2013-09-01T11:35:30.233 回答