Skip to content

Instantly share code, notes, and snippets.

@agarcian
Forked from stefanprodan/MonitorEndpoints.ps1
Created December 11, 2015 16:30
Show Gist options
  • Save agarcian/527e9e330fc0d940b345 to your computer and use it in GitHub Desktop.
Save agarcian/527e9e330fc0d940b345 to your computer and use it in GitHub Desktop.
Calling ASP.NET Web API endpoints at regular intervals can be easily done using Windows Task Scheduler and PowerShell’s Invoke-RestMethod. The following script makes a GET call for each supplied endpoint, if a call fails then the endpoint’s URL and the error details are sent to Windows Application Event Log.
#############################################
##
## Monitor ASP.NET WebAPI Enpoints
## Author: Stefan Prodan
## Date : 7 Apr 2014
## Company: VeriTech.io
#############################################
#Base url
$urlPrefix = "http://localhost/MyApp.Server/";
#Endpoints
$endpoints = @(
"api/status/ping",
"api/alerts/check",
"api/jobs/run"
);
$headers = @{"Client-Token"="my-app-client-secret-token"};
function Log([string] $url, $exception){
#Create EventLog source if it doesn't exist
$eventSource = "MyApp Job";
if (![System.Diagnostics.EventLog]::SourceExists($eventSource)){
New-Eventlog -LogName "Application" -Source $eventSource;
}
#Write warning to EventLog
$message = "Call failed URL: " + $url + " Details: " + $exception;
Write-EventLog -LogName "Application"`
-Source $eventSource -EventId 1 -EntryType Warning -Message $message;
}
#Call each endpoint
foreach ($endpoint in $endpoints) {
Write-Output -InputObject $endpoint;
try {
$response = Invoke-RestMethod -Uri ($urlPrefix + $endpoint)`
-method GET -ContentType "application/json" -Headers $headers;
Write-Output -InputObject $response;
}
catch {
Write-Output -InputObject $_.Exception.Response.StatusCode.Value__;
Log -url ($urlPrefix + $endpoint) -exception $_.Exception.Message;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment