posted on 29 November 2013

0 comments

Use PowerShell to execute a POST web request from a Windows Scheduled Task

TAGS: Asp.Net,PowerShell

In general I really enjoy using Windows Scheduled Tasks to run time specific jobs on a server. This could be anything from an emailing service to an export routine. The great thing about Task Scheduler is that it has a vast range or configurations options, triggers, actions, conditions etc. that caters for most of our situations. 

An issue we come across often enough is that we need to trigger a Url from the scheduled task to perform some action. 

Usually we would create a console application to trigger this web page as there should be security features built into the web request e.g.

  • Only run over HTTPS
  • Only accept POST requests
  • Include custom HTTP headers with unique GUID's for additional security checking

This is to secure the request and to ensure that not just anyone can trigger these events. Based on this it's pretty difficult to run this web request without a custom console application.

PowerShell to the rescue!!!

You can execute code within PowerShell, and best of all you can pass this code in as an argument to the application. 

powershell "$headers = @{ 'SomeHeader' = 'xxxxx' }; Invoke-WebRequest -Uri 'https://www.sample.com' -Method POST -Headers $headers; exit;"

Deconstructing the above it relates as follows

  • Start PowerShell
  • Create a headers variable with the custom key and value
  • Invoke a web request with the  following parameters
    • url
    • method (This will be POST)
    • headers – custom variable declared before
  • Exit PowerShell

Nice thing is you can paste this straight into the input for the scheduled task so no app or console app required. 

Simply paste the argument string into the "Add argument" field and you are good to go.

Hope someone benefits from this like I did

G

Gordon

Head of Development for Cergis.

Find out more about Gordon here.

0 comments

add your comment

Email me when other users reply