PowerShell HTTP Server Service Monitor

Below is a PowerShell script to setup an HTTP server, and display the current status of a service.  If the service changes to stopped or running, the hosted webpage will update the status.  Make sure to set your IP address in the $prefixAddr value, your service name in the $serviceName value, and set $timer to the amount of seconds you want to monitor.  Once you have started the script below, go to the $prefixAddr in a web browser.

capmonitor

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Text");

##Define Address, Service Name, and Timer
$prefixAddr = "http://192.168.1.50:80/";
$serviceName = "Spooler";
$timer = 100;

##Setup HTTP service
$httpServer = [System.Net.HttpListener]::new();
$httpServer.Start();
$httpServer.Prefixes.Add("$prefixAddr");
$context = $httpServer.GetContext();
$response = $context.Response;
$content = "<html><body><b>Service - $serviceName</b></body></html>";
[System.IO.Stream]$output = $response.OutputStream;
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content);
$output.Write($buffer,0,$buffer.Length);
$running = $FALSE;
$stopped = $FALSE;
$i = 0;

while ( $i -le $timer ) {
 $service = Get-Service -Name $serviceName;
 $serviceStatus = $service.Status;
 $timeStamp = Get-Date -Format T;
 ##Report if service is stopped
 if ( $serviceStatus -match "Stop" -and $stopped -ne $TRUE ) {
  $content = "<br>$serviceStatus - $timeStamp";
  [System.IO.Stream]$output = $response.OutputStream;
  $buffer = [System.Text.Encoding]::UTF8.GetBytes($content);
  $output.Write($buffer,0,$buffer.Length);
  $stopped = $TRUE;
  $running = $FALSE;
 }
 ##Report if service is running
 if ( $serviceStatus -match "Running" -and $running -ne $TRUE ) {
  $content = "<br>$serviceStatus - $timeStamp";
  [System.IO.Stream]$output = $response.OutputStream;
  $buffer = [System.Text.Encoding]::UTF8.GetBytes($content);
  $output.Write($buffer,0,$buffer.Length);
  $running = $TRUE;
  $stopped = $FALSE;
 }
 sleep(1);
 $i++;
}

$content = "<br><b>Monitor Complete - $timeStamp</b>";
[System.IO.Stream]$output = $response.OutputStream;
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content);
$output.Write($buffer,0,$buffer.Length);
$httpServer.Stop();


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s