I am using Invoke-WebRequest
in a SCOM PowerShell script to periodically monitor the availability of a URI. My script is fairly simple (since I have very little knowledge of 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()
In order to test this script, I did manual changes in the hosts
file on the client running the SCOM agent where I want to do the monitoring. Interestingly, the script succeeds in fetching the web endpoint even after the host is unreachable (tested this by pinging from that machine).
I did some further tests directly from the command line, and nothing changes. Even though I have no ping to the remote address, Invoke-WebRequest
still succeeds and fetches the web page. So what am I doing wrong here?
Without testing it, I'd guess it's dns caching.
The powershell-session probably caches the ip on the first request and ignores your hosts-file update(just uses the old working ip).
Try running your script before and after disconnecting your network adapter/cable to simulate server failure.
UPDATE: What I'm trying to say above is that the script would work perfectly if the servers is unavailable, but your simulation using the hosts-file is giving a "false-positive" (so ignore the results).
If you really need to test the script with editing the hosts file, disable .Net dns cache in the session by adding the following line at the start of your script: