Pass Parameters to a Windows Service – Simple Methods
In this article
Yes – you can pass parameters to a Windows Service by supplying them when you start the service (for example with sc start) and reading them in the service’s OnStart method.
What You\'ll Need
- A Windows machine with administrative rights.
- The service executable you want to configure.
- Command Prompt or PowerShell (run as administrator).
- Basic knowledge of C# (or the language used for the service) if you need to modify the code.
Step‑by‑Step
- Confirm the service can accept arguments. Open the service project in Visual Studio (or your preferred IDE) and locate the
OnStart(string[] args)override. If the method signature only containsOnStart(), change it toOnStart(string[] args)and add logic to parseargs. Example:protected override void OnStart(string[] args) { foreach (string arg in args) { // simple key=value parsing var parts = arg.Split('='); if (parts.Length == 2) { // store or act on the parameter } } } - Re‑build and install the service. Build the project, then install the service using
sc createorinstallutil.exe. Example withsc:sc create MyService binPath= "C:\Path\To\MyService.exe" start= auto
Ensure the command runs in an elevated prompt. - Stop the service if it is already running. Use the Services MMC snap‑in or run:
sc stop MyService
Wait until the state changes to STOPPED. - Start the service with parameters. The
sc startcommand accepts a space‑separated list of arguments after the service name. Enclose the entire argument list in quotes if any argument contains spaces. Example:sc start MyService "mode=debug port=8080"
In this case the service receives two arguments:mode=debugandport=8080. - Verify the parameters were received. Add logging (e.g., to the Windows Event Log or a text file) inside
OnStartto confirm the values. A quick test:EventLog.WriteEntry($"Service started with args: {string.Join(", ", args)}");Open Event Viewer → Windows Logs → Application to see the entry. - Alternative: Use a configuration file. If you prefer not to pass arguments each time, store settings in
app.configor a custom JSON file and read them inOnStart. This approach avoids the need forsc startparameters but still lets you change values without recompiling. - Alternative: Registry values. Some administrators store service‑wide settings under
HKLM\SYSTEM\CurrentControlSet\Services\MyService. Read those keys inOnStartif you need a central, machine‑wide location. - Restart the service to apply new parameters. After changing arguments, stop and start the service again using the same
sc startline. - Automate with a batch file (optional). Create a
.batfile that stops, starts with arguments, and logs the result. Example:@echo off sc stop MyService sc start MyService "mode=release path=\"C:\Data Files\""
Run the batch file as administrator for a one‑click deployment. - Document the accepted arguments. Keep a README or internal wiki that lists each supported key, its valid values, and default behavior. This prevents confusion for future operators.
Common Mistakes
- Trying to pass arguments with
net start. Thenet startcommand ignores extra tokens, so usesc startinstead. - Omitting quotes when an argument contains spaces. Without quotes, Windows treats the space as a separator and splits the argument incorrectly.
- Reading arguments from
Environment.GetCommandLineArgs()insideOnStart. The service host strips the original arguments; always use theargsparameter supplied toOnStart. - Changing the service code but forgetting to reinstall or restart the service. The old binary will continue to run until you explicitly stop and start it.
- Storing sensitive data (passwords, tokens) in plain‑text arguments. Arguments can be viewed with
tasklist /vor Process Explorer, so use secure storage instead.
Tips
- Use a consistent
key=valueformat; it simplifies parsing and reduces errors. - Validate each argument early in
OnStartand write a clear error to the Event Log if something is missing or malformed. - Limit the number of arguments to a reasonable size (under 2 KB) because the Service Control Manager truncates overly long command lines.
- When deploying to multiple machines, keep the argument list in a central script or configuration management tool (e.g., PowerShell DSC, Ansible) to avoid manual mistakes.
- If you need to change parameters while the service is running, implement a custom control command via
ServiceController.ExecuteCommandand handle it inOnCustomCommand.
Troubleshooting
If the service does not start or the arguments appear empty, follow these steps:
- Check the service status. Run
sc query MyServiceand ensure the state isRUNNING. If it showsSTOPPED, review the Event Log for start‑up errors. - Confirm you used an elevated prompt. Starting a service with arguments requires administrative privileges; otherwise
screturns "Access is denied". - Verify the exact command line. Open Task Manager, go to the "Details" tab, right‑click the service process, and choose "Properties" → "Command line". The displayed line should include the arguments you passed.
- Look for parsing errors. If your code expects
key=valuebut receives something else, the parsing loop may silently skip values. Add temporary debug logging to dump the rawargsarray. - Check for quoting issues. If an argument contains spaces, ensure the whole argument is wrapped in double quotes inside the outer quotes. Example:
sc start MyService "path=\"C:\Program Files\MyApp\data\"". - Review the service binary path. A mismatched
binPath(pointing to an older version) will cause the running executable to ignore new code. Re‑run thesc createorsc configcommand with the correct path. - Test with a simple argument. Try
sc start MyService "test"and log the received args. If this works, the problem lies with the specific argument format you used previously. - Re‑install the service as a last resort. Uninstall with
sc delete MyService, then recreate using the correct binary. This clears any stale configuration that might interfere.
Frequently Asked Questions
Can I pass arguments to a service that is already running?
No. The Service Control Manager only supplies arguments at start‑up. To change values you must stop the service, start it again with new arguments, or implement a custom control command.
Is there a limit to the length of the argument string?
Yes. The total command line, including the service name and all arguments, is limited to roughly 2 KB. Exceeding that limit truncates the tail of the argument list.
Do arguments appear in the Windows Event Viewer automatically?
Only if you write them there. The Service Control Manager does not log custom arguments; you need to log them yourself inside OnStart or via a separate logging framework.
Can I use PowerShell's Start-Service to pass arguments?
PowerShell's Start-Service does not expose a parameter for arguments. Use the native sc start command or invoke Start-Process with the service executable directly (which bypasses the SCM and is not recommended for production services).
What if my service is written in a language other than C#?
The principle is the same: the service entry point receives the argument array from the SCM. In C++ you would override ServiceMain and read lpServiceArgVectors. Adjust the parsing code to the language’s conventions.
Is it safe to store passwords in command‑line arguments?
Generally not. Command‑line arguments are visible to any user who can list processes. Use secure storage mechanisms such as the Windows Credential Manager or encrypted configuration files instead.