Run windows service in console

What is the best way to run a windows service as a console?

My current idea is to pass in an «/exe» argument and do the work of the windows service, then calling Application.Run().

The reason I’m doing this is to better debug a windows service and allow easier profiling of the code. The service is basically hosting .NET remoted objects.

asked Apr 15, 2009 at 0:21

Michael Hedgpeth's user avatar

Michael HedgpethMichael Hedgpeth

7,74210 gold badges48 silver badges66 bronze badges

This is how I do it. Give me the same .exe for console app and service. To start as a console app it needs a command line parameter of -c.

private static ManualResetEvent m_daemonUp = new ManualResetEvent(false);

[STAThread]
static void Main(string[] args)
{
    bool isConsole = false;

    if (args != null && args.Length == 1 && args[0].StartsWith("-c")) {
        isConsole = true;
        Console.WriteLine("Daemon starting");

        MyDaemon daemon = new MyDaemon();

        Thread daemonThread = new Thread(new ThreadStart(daemon.Start));
        daemonThread.Start();
        m_daemonUp.WaitOne();
    }
    else {
        System.ServiceProcess.ServiceBase[] ServicesToRun;
        ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service() };
        System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    }
}

answered Apr 15, 2009 at 0:31

sipsorcery's user avatar

sipsorcerysipsorcery

30.3k24 gold badges104 silver badges155 bronze badges

2

The Code Project site had a great article showing how to run a Windows Service in the Visual Studio debugger, no console app needed.

answered Apr 15, 2009 at 0:24

Dour High Arch's user avatar

Dour High ArchDour High Arch

21.5k29 gold badges76 silver badges90 bronze badges

Or

C:\> MyWindowsService.exe /?
MyWindowsService.exe /console
MyWindowsService.exe -console

answered Apr 15, 2009 at 0:24

Ray Lu's user avatar

This article provides a solution to facilitate debugging and administration of Windows Service created in C#/.Net.

The source code is available in the
MSDN Gallery.

Remark: all screenshots are created on a french Visual Studio, so the images are in french, but I’ll try to convert the terms in English.

Table of Contents

  • Motivation
  • Create a Windows Service
  • Debugging Windows Service
  • Convert a Service to Console Application for Debugging
    • Advantages
    • Disadvantages
    • Remarks
  • Install and Unistall the service
  • Start and Stop the service
  • Do More
    • Command to combine installation and startup
    • Run the services in interactive mode
  • See Also
  • Other Languages

Motivation

When we develop .Net Windows Services we are soon faced of debugging problem.

In addition we regularly start, stop the service, as well install and uninstall it. All of these actions require to use different commandlines (installutil, net start, etc.).

This article propose to transform our Windows Service to application console to allow to debug more easier, as well as manage all service through command line parameters, and thus simplify its management.

All that will be presented is not new, you will find a lot of articles on the subject across the Web, we just to gather all in one article, as a reminder.

Create a Windows Service

Quick reminder for the create of a service named «My Service»:

  • Start the new project creation
  • Select the template «Templates > Visual C# > Windows Desktop > Windows Service»

We rename the class «Service1» to «svcMyService» and the name of the service «My Service» in the property grid opened:

So, in the Solution Explorer, we rename the file «Service1.cs» of the service «svcMyService.cs»:

The underlying files will be automatically renamed.

The last step is to create a service installer. From the designer of the service (if it’s closed, open it with a double click on «svcMyService.cs» from the Solution Explorer), right click on the designer and select «Add installer».

In the opened designer, select «serviceProcessInstaller1» to change the running service account, in our case choose «LocalSystem».

By selecting «serviceInstaller1» we can change the display informations in the services manager.

Build the program with the menu «Build > Build the solution». If you run the program a dialog is displayed to inform you that is a service that need to be installed and started.

We make a test by installing the service, and by starting it:

  • Open a command shell as administrator
  • Go to the folder where is the compiled service «bin\debug» of the folder solution

We can open directly the folder of the solution from the Solution Explorer, right click on the project et choose «Open in the Explorer» and navigate to «bin\debug». On Windows 8.1 use the menu «File > Open command shell > Open command shell as administrator».

Install the service:

"%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" WinServiceTest.exe

And we start our service.

net start "My Service"

Normally all it works:

  • In the exe folder we can find the log files.
  • In the Services Manager we can find our service (with the informations defined in the service installer).
  • In the events viewer a new source is available «My Service» if you keep «True» the value of «AutoLog» property from the service designer.

We can stop all:

net stop "My Service""%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" /u WinServiceTest.exe

Debugging Windows Service

Reminder : to debug a service you need to do many things:

  • Install the service with «InstallUtil.exe»
  • Start the service with «net start»
  • Run Visual Studio as Administrator
  • Attach the debuger to the running service

Of course, before update your code and recompile your service, you must at least stop your service with «net stop».

This whole procedure is sometimes tedious, and also poses a problem in debugging, if the service does not correctly startup, you haven’t time to attach the debugger to trace what happens.

Convert a Service to Console Application for Debugging

The idea to help us debugging is to create a console application that simulate the service execution when it run under Visual Studio.

The first step is to change the project application type.

  • Right click on the service project («WinServiceTest» in our case) and select «Properties».
  • In the «Application» tab, «Output type» select «Console Application» («Windows Application» by default).
  • Save the changes.

After, the idea is to check if we are in service mode or debug mode, for this we need to known if we are in interactive mode, we use the
Environment.UserInteractive property for that, and we need to know if we are in debug mode with the
System.Diagnostics.Debugger.IsAttached property.

In the «Program.cs» file we change the Main code like this

/// <summary>

/// Main entry point of the application.

/// </summary>

static
void
Main()

{

    // Initialize the service to start

    ServiceBase[] ServicesToRun;

    ServicesToRun =
new
ServiceBase[]

    {

        new
svcMyService()

    };

    // In interactive and debug mode ?

    if
(Environment.UserInteractive && System.Diagnostics.Debugger.IsAttached)

    {

        // Simulate the services execution

        RunInteractiveServices(ServicesToRun);

    }

    else

    {

        // Normal service execution

        ServiceBase.Run(ServicesToRun);

    }

}

Then we adding the «RunInteractiveServices» method that start each service :

/// <summary>

/// Run services in interactive mode

/// </summary>

static
void
RunInteractiveServices(ServiceBase[] servicesToRun)

{

    Console.WriteLine();

    Console.WriteLine("Start the services in interactive mode.");

    Console.WriteLine();

    // Get the method to invoke on each service to start it

    MethodInfo onStartMethod =
typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);

    // Start services loop

    foreach
(ServiceBase service in
servicesToRun)

    {

        Console.Write("Starting {0} ... ", service.ServiceName);

        onStartMethod.Invoke(service,
new
object
[] { new
string[] { } });

        Console.WriteLine("Started");

    }

    // Waiting the end

    Console.WriteLine();

    Console.WriteLine("Press a key to stop services et finish process...");

    Console.ReadKey();

    Console.WriteLine();

    // Get the method to invoke on each service to stop it

    MethodInfo onStopMethod =
typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);

    // Stop loop

    foreach
(ServiceBase service in
servicesToRun)

    {

        Console.Write("Stopping {0} ... ", service.ServiceName);

        onStopMethod.Invoke(service,
null);

        Console.WriteLine("Stopped");

    }

    Console.WriteLine();

    Console.WriteLine("All services are stopped.");

    // Waiting a key press to not return to VS directly

    if
(System.Diagnostics.Debugger.IsAttached)

    {

        Console.WriteLine();

        Console.Write("=== Press a key to quit ===");

        Console.ReadKey();

    }

}

Each service start on its own thread, we do not have to manage it.

Advantages

Therefore the first advantage is to be able to debug the entire chain to start your service.

Another advantage is that you can create a log system that display message on the console, it’s direct and readable.

Disadvantages

However ther are some disadvantages.

A Windows Service generally run as an Administrator account (LocalSystem, LocalNetwork, etc.), wich can cause some rights problems depending of what the service doing. You can resolve this problem, by running Visual Studio as Administrator,
and the when the service is launched it get the administrator rights.

A service, when it starting, do some tasks (create an event log source, etc.), our small application don’t do that. It’s your job to d all it’s needed for your service.

Remarks

Caution, this mode don’t make you free to debug as service mode, it allows you to quickly debug your service, but your to test in service mode to ensure the correct behavior of the service in is normal mode.

Install and Unistall the service

A service for running, need to be installed (it is registered to the Windows ServiceManager). To install a .Net Service we need to run the command «InstallUtil.exe» in the .Net Framework folder.

This command is sometimes a bit long to write, even when it is necessary to install the service with an installer, it is necessary to locate the folder of the corresponding framework, etc.

As we have now a console application, we can use it to facilitate the work. For example with the command line arguments to install/uninstall the service.

To manage the install/uninstall service we can use the class
System.Configuration.Install.ManagedInstallerClass that contains some helpers methods to do it.

We will change our console application to supports ‘commands’ like
install and uninstall.

We will need to change the application behavior:

  • if we are in debug mode we run the services in interactive mode
  • if we are in interactive mode, we check if we have somme commands. In this case we run the commands, otherwise we print a message usage.
  • if we are not in interative mode, we run normally the services.

We create a HasCommand method to check if there are a command in the command line:


/// <summary>

/// Helper for check if we are a command in the command line arguments

/// </summary>

static bool HasCommand(String[] args, String command)

{

    if (args == null || args.Length == 0 || String.IsNullOrWhiteSpace(command)) return false;

    return args.Any(a => String.Equals(a, command, StringComparison.OrdinalIgnoreCase));

}

The we change the Main method to supports arguments, and to process the commands:


/// <summary>

/// Main entry point of the application.

/// </summary>

static void Main(String[] args)

{

    // Initialize the service to start

    ServiceBase[] ServicesToRun;

    ServicesToRun = new ServiceBase[]

    {

        new svcMyService()

    };

    // In interactive mode ?

    if (Environment.UserInteractive)

    {

        // In debug mode ?

        if (System.Diagnostics.Debugger.IsAttached)

        {

            // Simulate the services execution

            RunInteractiveServices(ServicesToRun);

        }

        else

        {

            try

            {

                bool hasCommands = false;

                // Having an install command ?

                if (HasCommand(args, "install"))

                {

                    ManagedInstallerClass.InstallHelper(new String[] { typeof(Program).Assembly.Location });

                    hasCommands = true;

                }

                // Having an uninstall command ?

                if (HasCommand(args, "uninstall"))

                {

                    ManagedInstallerClass.InstallHelper(new String[] { "/u", typeof(Program).Assembly.Location });

                    hasCommands = true;

                }

                // If we don't have commands we print usage message

                if (!hasCommands)

                {

                    Console.WriteLine("Usage : {0} [command] [command ...]", Environment.GetCommandLineArgs());

                    Console.WriteLine("Commands : ");

                    Console.WriteLine(" - install : Install the services");

                    Console.WriteLine(" - uninstall : Uninstall the services");

                }

            }

            catch (Exception ex)

            {

                var oldColor = Console.ForegroundColor;

                Console.ForegroundColor = ConsoleColor.Red;

                Console.WriteLine("Error : {0}", ex.GetBaseException().Message);

                Console.ForegroundColor = oldColor;

            }

        }

    }

    else

    {

        // Normal service execution

        ServiceBase.Run(ServicesToRun);

    }

}

Start and Stop the service

Same as the installation, for starting and stopping our service we must use a command «net start/stop» or the service manager.

For the same reasons as before, we will use some command line arguments of our console application. And for this we use the
System.ServiceProcess.ServiceController class.

So we add deux commands start and stop between our two commands insall and uninstall.


...

// Having a start command ?

if (HasCommand(args, "start"))

{

    foreach (var service in ServicesToRun)

    {

        ServiceController sc = new ServiceController(service.ServiceName);

        sc.Start();

        sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));

    }

    hasCommands = true;

}

// Having a stop command ?

if (HasCommand(args, "stop"))

{

    foreach (var service in ServicesToRun)

    {

        ServiceController sc = new ServiceController(service.ServiceName);

        sc.Stop();

        sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));

    }

    hasCommands = false;

}

...

How we process the commands, allows us to combine installation and startup in one command line. Same for stop and uninstall.

WinServiceTest.exe install start
WinServiceTest.exe uninstall stop

The order of the commands in the command line is not important, because we process the commands in the good order (we test ‘stop’ before ‘uninstall’).

Do More

Of course we can add more commands helpers.

Command to combine installation and startup

We can create a command to process in one command the installation and the startup. Same as for stopping and uninstall the service.

In our example, we implement it with the commands ‘start-services’ and ‘stop-services’, we process these commands first.

Run the services in interactive mode

We run the services in interactive mode only in debug mode. But it could be usefull to run the services in interactive mode. Si we can add a command for it.

In our example, we implement it with the command ‘run-services’.


See Also

  • Source code on MSDN Gallery
  • Source code on Github
  • Original French Blog Post

Other Languages

  • C# : Service Windows en mode console pour le débogage et l’administration
    (fr-FR)

on August 15, 2010

We normally use Services.msc to start or stop or disable or enable any service. We can do the same from windows command line also using net and sc utilities. Below are commands for controlling the operation of a service.

Command to stop a service:

net stop servicename

To start a service:

net start servicename

You need to have administrator privileges to run net start/stop commands. If you are just a normal user on the computer, you would get an error like below.

C:\>net start webclient
System error 5 has occurred.
Access is denied.
C:\>

To disable a service:

sc config servicename start= disabled

To enable a service:

sc config servicename start= demand

To make a service start automatically with system boot:

sc config servicename start= auto

Note: Space is mandatory after ‘=’ in the above sc commands.

This SC command works on a Windows 7 machine and also on the down-level editions of Windows i.e Windows XP/2003 and Windows Vista. Again, if you do not have administrator previliges you would get the below error.

C:\>sc config webclient start= auto
[SC] OpenService FAILED 5:
Access is denied.

Note that the service name is not the display name of a service. Each service is given a unique identification name which can be used with net or sc commands. For example, Remote procedure call (RPC) is the display name of the service. But the service name we need to use in the above commands is RpcSs.
So to start Remote procedure call service the command is:

net start RpcSsTo stop Remote procedure call service
net stop RpcSs

These service names are listed below for each service. The first column shows the display name of a service and the second column shows the service name that should be used in net start or net stop or sc config commands.

Display Name of the service ServiceName which should be used with ‘net’ and ‘sc config’ commands.
Alerter Alerter
Application Layer Gateway Service ALG
Application Management AppMgmt
ASP.NET State Service aspnet_state
Windows Audio AudioSrv
Background Intelligent Transfer Service BITS
Computer Browser Browser
Bluetooth Support Service BthServ
Bluetooth Service btwdins
SMS Agent Host CcmExec
Indexing Service CiSvc
ClipBook ClipSrv
.NET Runtime Optimization Service v2.0.50727_X86 clr_optimization_v2.0.50727_32
COM+ System Application COMSysApp
Cryptographic Services CryptSvc
Cisco Systems, Inc. VPN Service CVPND
DCOM Server Process Launcher DcomLaunch
DHCP Client Dhcp
Logical Disk Manager Administrative Service dmadmin
Logical Disk Manager dmserver
DNS Client Dnscache
Lenovo Doze Mode Service DozeSvc
Error Reporting Service ERSvc
Event Log Eventlog
COM+ Event System EventSystem
Intel(R) PROSet/Wireless Event Log EvtEng
Fast User Switching Compatibility FastUserSwitchingCompatibility
Windows Presentation Foundation Font Cache 3.0.0.0 FontCache3.0.0.0
Group Policy Monitor GPMON_SRV
Help and Support helpsvc
HID Input Service HidServ
HTTP SSL HTTPFilter
ThinkPad PM Service IBMPMSVC
Windows CardSpace idsvc
IMAPI CD-Burning COM Service ImapiService
iPassConnectEngine iPassConnectEngine
iPassPeriodicUpdateApp iPassPeriodicUpdateApp
iPassPeriodicUpdateService iPassPeriodicUpdateService
IviRegMgr IviRegMgr
Server lanmanserver
Workstation lanmanworkstation
Lenovo Camera Mute LENOVO.CAMMUTE
Lenovo Microphone Mute Lenovo.micmute
TCP/IP NetBIOS Helper LmHosts
Intel(R) Management and Security Application Local Management Service LMS
McAfee Framework Service McAfeeFramework
McAfee McShield McShield
McAfee Task Manager McTaskManager
Machine Debug Manager MDM
Messenger Messenger
NetMeeting Remote Desktop Sharing mnmsrvc
Distributed Transaction Coordinator MSDTC
Windows Installer MSIServer
Net Driver HPZ12 Net Driver HPZ12
Network DDE NetDDE
Network DDE DSDM NetDDEdsdm
Net Logon Netlogon
Network Connections Netman
Net.Tcp Port Sharing Service NetTcpPortSharing
Network Location Awareness (NLA) Nla
NT LM Security Support Provider NtLmSsp
Removable Storage NtmsSvc
Microsoft Office Diagnostics Service odserv
Office Source Engine ose
Plug and Play PlugPlay
Pml Driver HPZ12 Pml Driver HPZ12
IPSEC Services PolicyAgent
Power Manager DBC Service Power Manager DBC Service
Protected Storage ProtectedStorage
Remote Access Auto Connection Manager RasAuto
Remote Access Connection Manager RasMan
Remote Desktop Help Session Manager RDSessMgr
Intel(R) PROSet/Wireless Registry Service RegSrvc
Routing and Remote Access RemoteAccess
Remote Registry RemoteRegistry
Remote Procedure Call (RPC) Locator RpcLocator
Remote Procedure Call (RPC) RpcSs
QoS RSVP RSVP
Intel(R) PROSet/Wireless WiFi Service S24EventMonitor
Security Accounts Manager SamSs
Smart Card SCardSvr
Task Scheduler Schedule
Secondary Logon seclogon
System Event Notification SENS
Windows Firewall/Internet Connection Sharing (ICS) SharedAccess
Shell Hardware Detection ShellHWDetection
Print Spooler Spooler
System Restore Service srservice
SSDP Discovery Service SSDPSRV
Windows Image Acquisition (WIA) stisvc
System Update SUService
MS Software Shadow Copy Provider SwPrv
Performance Logs and Alerts SysmonLog
Telephony TapiSrv
Terminal Services TermService
Themes Themes
ThinkVantage Registry Monitor Service ThinkVantage Registry Monitor Service
Telnet TlntSvr
On Screen Display TPHKSVC
Distributed Link Tracking Client TrkWks
TVT Scheduler TVT Scheduler
Windows User Mode Driver Framework UMWdf
Intel(R) Management & Security Application User Notification Service UNS
Universal Plug and Play Device Host upnphost
Uninterruptible Power Supply UPS
Volume Shadow Copy VSS
Windows Time W32Time
WebClient WebClient
Windows Management Instrumentation winmgmt
Portable Media Serial Number Service WmdmPmSN
Windows Management Instrumentation Driver Extensions Wmi
WMI Performance Adapter WmiApSrv
Security Center wscsvc
Automatic Updates wuauserv
SMS Remote Control Agent Wuser32
Wireless Zero Configuration WZCSVC
Network Provisioning Service xmlprov

When working on a Windows Service project you may want to run it as a Console App so you can see what’s going on.

If you try to run the service in Visual Studio you’ll get an error that says: “Cannot start service from the command line or a debugger. A Windows Service must first be installed… .”

You really only have two options:

  1. Install the service and look at the logs. This is tedious and slows down development.
  2. Conditionally run the program as a console app

In this article I’ll explain how to run it as a console app.

1 – Set the project output type to Console Application

Check which scenario below matches your situation.

Note: If you don’t change your output type to Console App you’ll get an exception “System.InvalidOperationException: ‘Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.’

If you already have a Windows Service project

Simply change the Output type to Console Application.

Project Application tab, showing Output type = Console Application

If you are starting a new project from scratch

Create a Windows Service project. Then change the Output type to Console Application.

2 – Conditionally run as console or as a service based on a command line argument

Check for the “/CONSOLE” command line argument to determine if you need to run as a service or as a console app.

If you are running as a service, the framework will call TestService.OnStart(), and then you’ll call TestService.StartService(). If you’re running as a console app you’ll call TestService.StartService(). In both cases you’ll end up calling the StartService() method.

using System;
using System.Linq;
using System.ServiceProcess;

namespace WindowsServiceAsConsole
{
    static class Program
    {
        public static void Main(string[] args)
        {
            if (args.FirstOrDefault()?.ToUpper() == "/CONSOLE")
            {
                RunAsConsole();
            }
            else
            {
                RunAsService();
            }
        }
        private static void RunAsConsole()
        {
            TestService serv = new TestService();
            serv.StartService();

            Console.WriteLine("Running service as console. Press any key to stop.");
            Console.ReadKey();

            serv.Stop();
        }
        private static void RunAsService()
        {
            /* Warning: Don't load the object graph or 
             * initialize anything in here. 
             * 
             * Initialize everything in TestService.StartService() instead
             */
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new TestService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

Code language: C# (cs)

3 – Add StartService() to the service class

The key here is to create a method that is called by both the service and console app. The framework will call OnStart() when starting as a service. It’s important that all you do is call StartService() in a new thread here.

Note: Avoid doing any initialization in OnStart(). Windows enforces a “startup time” for services, and your service will not finish starting up if it’s taking too long in OnStart().

using System;
using System.ServiceProcess;

namespace WindowsServiceAsConsole
{
    public partial class TestService : ServiceBase
    {
        public TestService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            new System.Threading.Thread(StartService).Start();
        }

        protected override void OnStop()
        {
        }

        internal void StartService()
        {            
            /* 
                This is the true composition root for a service,
                so initialize everything in here
            */
            Console.WriteLine("Starting service");
        }
    }
}

Code language: C# (cs)

4 – Add the /CONSOLE command line argument in the build options

To automatically run as a console app every time you start the program from Visual Studio, you can add the /CONSOLE flag as a command line argument. You should only do this for the Debug build configuration.

Project Debug tab with Command line arguments = /CONSOLE

Make sure you’re not passing in /CONSOLE for the Release build configuration, otherwise when you deploy it’ll run as a console app in production.

Project Debug tab with Command line arguments empty for Release configuration

Note: You can still run this as console app in production manually. Just open a command line and execute your exe with the /CONSOLE command line argument, like this:

PowerShell command: ./WindowsServiceAsConsole /CONSOLE

Службы Windows (Windows Service) — приложения (программы), работающие в фоновом режиме, без пользовательского интерфейса. Грубо говоря, некий аналог демонов в Unix системах.

Управление работой служб с помощью консоли управления.

Для управления службами в Windows существует графическая утилита — службы (services.msc), для ее запуска необходимо перейти:

Панель управления (Control Panel) —> Администрирование (Administrative Tools) —>  Службы (Services) или в строке поиска меню Пуск (Start) ввести services.msc.

windows-services

Вид окна службы services.msc.

Из этой консоли можно просматривать, запускать, останавливать, изменять параметры и тип запуска служб.

Различные варианты запуска служб.

1) Автоматически (отложенный запуск) — служба будет запущена спустя некоторое время после старта операционной системы, используется для служб, ненужных при загрузке операционной системы, позволяет оптимизировать процесс загрузки.

2) Автоматически — служба будет запущена при старте операционной системы.

3) Вручную — служба запускается пользователем, приложениями или другими службами.

4) Отключена – службу  нельзя запустить.

Примечание: Существует еще один вариант (обязательная служба) — автоматически запускается и пользователь не может остановить эту службу).

Управление службами из командной строки.

Службами window можно управлять не только используя графическую утилиту, но и из командной строки windows cmd. Для запуска переходим в пункт меню: Пуск —> Выполнить —> В строку вводим команду cmd.exe. Ниже приведу команды для управления службами.

Остановка службы.

sc stop [имя_службы]

Запуск службы.

sc start [имя_службы]

Удаление службы.

sc delete [имя_службы]

Установка режима запуска службы:

sc config [имя_службы] start= [параметр_запуска]
	параметр_запуска:
		auto - автоматически.
		demand - вручную.
		disabled - отключена.
Примечание: После start= должен идти обязательно пробел.

Запрос данных конфигурации для службы.

sc qc [имя_службы]

Просмотр всех служб:

sc query

Для удобства чтения выводимой информации используем утилиту more.

sc query | more

Для копирования вывода в буфер используем утилиту clip.

sc query | clip

Вывод справки по команде sc.

sc ?

Примечание: Если имя службы содержит пробелы, то необходимо его заключить в кавычки.

sc delete “Events Utility”

Особенностью служб является то, что они запускаются от имени пользователя LocalSystem — обладающего полными правами в системе.

Список всех служб расположен в ветке реестра:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

На этом заканчиваем знакомство со службами windows. Надеюсь статья была полезная.

  • Run windows programs on mac
  • Run exe from terminal windows
  • Runtime broker в диспетчере задач windows 10 что это
  • Run windows programs on linux
  • Run dll устранение ошибки windows 10 не найден указанный модуль