Monday, November 16, 2009

Using Command-line arguments in Windows Services – a “gotcha”

This can’t really be considered a “gotcha” more than just a “pay careful attention to the perhaps unintuitive documentation” scenario.  Also, this assumes basic knowledge of creating Windows Services.

So here’s the situation: I wrote a Windows Service, and I wanted to optionally enable verbose debug output (since services are a bit of a pain to debug) using a command-line option.  Services, after all, can be started with command-line arguments.  But regardless of what I entered as the command-line arguments, the OnStart(string[] args) method of my service would always report that “args” was empty – that is, no arguments.

After some quick Bingoogling, here’s what I found:

The arguments in the args parameter array can be set manually in the properties window for the service in the Services console. The arguments entered in the console are not saved; they are passed to the service on a one-time basis when the service is started from the control panel.

I still thought that I was doing the right thing, by going to my service’s properties, typing command-line arguments, clicking OK and then right clicking the service and choosing Start:

image

image

But no luck!  The solution was very simple: Click Start from within the Properties window.  As soon as you click OK (which intuitively would seem to save the changes to the Start parameters, as is the case in every other properties dialog in the history of mankind), the Start parameters disappear.