Start windows service with cmd

Start or stop Windows service from command line (CMD)

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:

To start a service:

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.

To disable a service:

To enable a service:

To make a service start automatically with system boot:

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.

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:

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.

start start

Запускает отдельное окно командной строки для запуска указанной программы или команды. Starts a separate Command Prompt window to run a specified program or command.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
Задает заголовок, отображаемый в строке заголовка окна командной строки . Specifies the title to display in the Command Prompt window title bar.
/d

Указывает каталог запуска. Specifies the startup directory. /i /i Передает Cmd.exe среду запуска в новое окно командной строки . Passes the Cmd.exe startup environment to the new Command Prompt window. Если параметр /i не указан, используется текущая среда. If /i is not specified, the current environment is used. Служит для сворачивания (/min) или развертывания (/Макс) нового окна командной строки . Specifies to minimize (/min) or maximize (/max) the new Command Prompt window. Запускает 16-разрядные программы в отдельном пространстве памяти (/сепарате) или общей памяти (/Shared). Starts 16-bit programs in a separate memory space (/separate) or shared memory space (/shared). Эти параметры не поддерживаются на 64-разрядных платформах. These options are not supported on 64-bit platforms. Запускает приложение в указанном классе приоритета. Starts an application in the specified priority class. /аффинити /affinity Применяет указанную маску схожести процессоров (выраженную в виде шестнадцатеричного числа) к новому приложению. Applies the specified processor affinity mask (expressed as a hexadecimal number) to the new application. /Wait /wait Запускает приложение и ждет его завершения. Starts an application and waits for it to end. /елевате /elevate Запускает приложение от имени администратора. Runs application as administrator. /b /b Запускает приложение, не открывая новое окно командной строки . Starts an application without opening a new Command Prompt window. Обработка CTRL + C игнорируется, если приложение не поддерживает обработку CTRL + C. CTRL+C handling is ignored unless the application enables CTRL+C processing. Чтобы прервать работу приложения, используйте сочетание клавиш CTRL + BREAK. Use CTRL+BREAK to interrupt the application. [ [

. ]] Указывает запускаемую команду или программу. Specifies the command or program to start.

Указывает параметры для передачи в команду или программу. Specifies parameters to pass to either the command or the program. /? /? Отображение справки в командной строке. Displays help at the command prompt.

Комментарии Remarks

Вы можете запускать неисполняемые файлы с помощью сопоставления файлов, вводя имя файла в виде команды. You can run non-executable files through their file association by typing the name of the file as a command.

При выполнении команды, содержащей строку CMD в качестве первого маркера без квалификатора расширения или пути, команда CMD заменяется значением переменной COMSPEC. If you run a command that contains the string CMD as the first token without an extension or path qualifier, CMD is replaced with the value of the COMSPEC variable. Это не позволяет пользователям выбирать cmd из текущего каталога. This prevents users from picking up cmd from the current directory.

Если вы запускаете приложение с 32-битным графическим пользовательским интерфейсом (GUI), программа cmd не ждет завершения работы приложения, прежде чем вернуться в командную строку. If you run a 32-bit graphical user interface (GUI) application, cmd does not wait for the application to quit before returning to the command prompt. Такое поведение не происходит при запуске приложения из командного скрипта. This behavior does not occur if you run the application from a command script.

При выполнении команды, использующей первый токен, который не содержит расширение, Cmd.exe использует значение переменной среды ПАСЕКСТ, чтобы определить, какие расширения следует искать и в каком порядке. If you run a command that uses a first token that does not contain an extension, Cmd.exe uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. Значение по умолчанию для переменной ПАСЕКСТ: The default value for the PATHEXT variable is:

Обратите внимание, что синтаксис аналогичен переменной PATH с точкой с запятой (;) Отделение каждого расширения. Note that the syntax is the same as the PATH variable, with semicolons (;) separating each extension.

При поиске исполняемого файла, если нет совпадения с каким-либо расширением, запустите проверку, чтобы проверить, совпадает ли имя с именем каталога. When searching for an executable file, if there is no match on any extension, start checks to see if the name matches a directory name. Если это так, то Start открывает Explorer.exe по этому пути. If it does, start opens Explorer.exe on that path.

Примеры Examples

Чтобы запустить программу MyApp из командной строки и использовать текущее окно командной строки , введите: To start the Myapp program at the command prompt and retain use of the current Command Prompt window, type:

Чтобы просмотреть раздел справки по командной строке в отдельном окне командной строки с развернутым окном, введите: To view the start command-line help topic in a separate maximized Command Prompt window, type:

Windows: Запуск Службы — CMD & PowerShell

Служба в Windows может быть запущена с помощью утилиты Service Manager.

Для запуска Service Manager GUI, нажмите клавишу Win для открытия меню «Пуск», наберите services , чтобы найти Service Manager и нажмите Enter .

Также служба в Windows может быть запущена из командной строки (CMD) или PowerShell.

В данной заметке я показываю, как запустить, остановить или узнать состояние службы в Windows с помощью командной строки (CMD) или PowerShell.

Дельный Совет: Вывести список служб в Windows из CMD! Читать далее →

Запуск Службы Из Командной Строки (CMD)

Во избежании ошибки «Access is denied«, запустите CMD с правами администратора: нажмите клавишу Win , чтобы открыть меню «Пуск», наберите cmd , чтобы найти командную строку и нажмите комбинацию Ctrl + Shift + Enter , чтобы запустить командную строку от имени администратора.

Используйте следующие команды, чтобы запустить, остановить или проверить статус службы в Windows из командной строки (CMD).

Узнать состояние службы:

Дельный Совет: Убить зависший процесс в Windows из CMD! Читать далее →

Запуск Службы Из PowerShell

Во избежании ошибки «Access is denied«, запустите PowerShell с правами администратора: нажмите клавишу Win , чтобы открыть меню «Пуск», наберите powershell , чтобы найти командную строку и нажмите комбинацию Ctrl + Shift + Enter , чтобы запустить PowerShell от имени администратора.

Используйте следующие команды, чтобы запустить, остановить или проверить статус службы в Windows из PowerShell.

start

Starts a separate Command Prompt window to run a specified program or command.

Syntax

Parameters

Parameter Description
Specifies the title to display in the Command Prompt window title bar.
/d

Specifies the startup directory. /i Passes the Cmd.exe startup environment to the new Command Prompt window. If /i is not specified, the current environment is used. Specifies to minimize (/min) or maximize (/max) the new Command Prompt window. Starts 16-bit programs in a separate memory space (/separate) or shared memory space (/shared). These options are not supported on 64-bit platforms. Starts an application in the specified priority class. /affinity Applies the specified processor affinity mask (expressed as a hexadecimal number) to the new application. /wait Starts an application and waits for it to end. /elevate Runs application as administrator. /b Starts an application without opening a new Command Prompt window. CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application. [ [

. ]] Specifies the command or program to start.

Specifies parameters to pass to either the command or the program. /? Displays help at the command prompt.

Remarks

You can run non-executable files through their file association by typing the name of the file as a command.

If you run a command that contains the string CMD as the first token without an extension or path qualifier, CMD is replaced with the value of the COMSPEC variable. This prevents users from picking up cmd from the current directory.

If you run a 32-bit graphical user interface (GUI) application, cmd does not wait for the application to quit before returning to the command prompt. This behavior does not occur if you run the application from a command script.

If you run a command that uses a first token that does not contain an extension, Cmd.exe uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. The default value for the PATHEXT variable is:

Note that the syntax is the same as the PATH variable, with semicolons (;) separating each extension.

When searching for an executable file, if there is no match on any extension, start checks to see if the name matches a directory name. If it does, start opens Explorer.exe on that path.

Examples

To start the Myapp program at the command prompt and retain use of the current Command Prompt window, type:

To view the start command-line help topic in a separate maximized Command Prompt window, type:

Start windows service with cmd

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1″ :pagination=»pagination» :callback=»loadData» :options=»paginationOptions»>

Читайте также:  Кровля профи для windows
Оцените статью