Wednesday, April 10, 2019

monitoring applications

Part of a decent monitoring scheme is making sure business critical things are running all the time.  PRTG and powershell are a great way to do that.

$errorFound = $false


try
{
    if( -not (get-process -ProcessName "blah" -ErrorAction 'silentlycontinue' ))
    {
        throw 
    }
    $textVal = "OK"
    $errorFound = $false
}
catch
{
    $errorFound  = $true
    $textVal = "blah Not Running"
}



write-output ""
write-output ""

write-output "blahProcessRunning"


"Status"
   

"1"
"1"
"
"     



if($errorFound)
{
    write-output "0"
    write-output "1"
    $textVal = "blah Process not running." 

}
else
{
        "0"
        $textVal = "OK"
        "1"
    
}

"" + $textVal + ""
write-output ""
write-output ""
write-output ""

write-output "BlahProcessRunning"


"Status"
   

"1"
"1"
"
"     



if($errorFound)
{
    write-output "0"
    write-output "1"
    $textVal = "blah Process not running." 

}
else
{
        "0"
        $textVal = "OK"
        "1"
    
}

"" + $textVal + ""
write-output "
"

Note: Blogger as far as I know is doesn't have a good way to post full code.  So there's a bit more to it than this, but it's all opening and closing brackets. 

Ok, so there's all the code.  Most of it is pretty dull.

The heavy lifting is done by the get-process ProcessName "blah" section.  Which is pretty self explanatory.  Works great when the process happens to be running.  The problem is what happens when the process doesn't run.

When it doesn't run, you get red powershell text.  Which is what we don't want. Adding -erroraction "silentlycontinue" gets rid of the error text.

But now it fails and doesn't tell us anything.  Also not what we want.

So try-catch.

Which doesn't quite properly work.  It doesn't give any output at all.

The answer was the if(-not ((process)) ) bit followed by the {throw}

So, if you get some sort of failure, silently continue and throw an error.
Which the catch picks up.

And now we've got some nicely formatted text that changes based on whether the process is or is not running.  And with business critical processes, that's what you need.

Now, get-process dumps a lot of interesting data that you could feed back to PRTG.  Frankly, I wasn't that concerned.  I just wanted to know whether the process was running.

As for install procedure, let's not skip that.

Install a PRTG remote probe.
Drop this file in the CustomSensors\EXEXML directory.

Change the policy for the x86 version of powershell to unrestricted.
Or sign the code with your own code signing cert.  I don't know how to do that.  So  I go with the first.

That's in c:\windows\syswow64\windowspowershell\1.0\powershell.exe

Not the same one as opening a command prompt or searching for powershell.exe.

So there you go.  Alert as your company dictates and or want.