С помощью командлета Get-Service можно получить список всех установленных в системе служб, их состояние и тип запуска. Этот и другие командлеты для получения статуса и управления службами Windows впервые появился в версии Powershell 1.0. В этой статье мы разберем типовые примеры использования Get-Service для получения статуса служб на локальном или удаленных компьютерах, типе запуска служб и покажем как определять зависимости служб.
Получить список служб, установленных на локальном или удаленном компьютере можно с помощью командлета Get-Service. Команда Get-Service без параметров возвращает список всех служб на локальной системе.
Get-Service
Данная команда выведет список всех служб и их статус (запущена или остановлена) и отображаемое имя (Display Name).
Если вам нужно вывести только запушенные службы, воспользуемся такой командой:
Get-Service | Where-Object {$_.Status -EQ "Running"}
Оператор конвейера (|) передает результаты командлету Where-Object, который отбирает только те службы, для которых параметр Status имеет значение Running. В том случае, если нужно вывести только остановленные службы, укажите значение Stopped.
Получить все свойства объекта службы можно с помощью командлета Get-Member.
get-service | get-member
Как вы видите, данный объект имеет тип (Typename) System.ServiceProcess.ServiceController. На скриншоте выведены все доступные свойства и методы объектов служб в системе (большинство из них не используются при отображении по умолчанию).
Чтобы вывести определенные свойства службы, нужно воспользоваться возможностями выбора свойств объектов с помощью командлета Select. Например, нам нужно вывести имя, статус и доступные возможности службы Windows Update:
get-service wuauserv | select Displayname,Status,ServiceName,Can*
DisplayName : Windows Update
Status : Stopped
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
К примеру, чтобы получить тип запуска служб Windows, выполните команду (работает в PowerShel 5.1):
Get-Service | select -property name,starttype
Можно отфильтровать полученный список по имени службы, используя звездочку как подстановочный знак:
get-service wi*
Так можно отсортировать список служб компьютера в порядке убывания по значению свойства Status. Запущенные службы отображаются раньше остановленных.
get-service s* | sort-object status -Descending
В том случае, если нужно проверить наличие (существование) службы в системе (как правило, это может понадобиться в различных скриптах), вы можете воспользоваться такой конструкцией:
if (Get-Service "ServiceTest" -ErrorAction SilentlyContinue)
{
Write-host "ServiceTest exists"
}
Командлет Get-Service можно использовать для получения статуса служб не только на локальном, но и удаленных компьютерах. Для этого нужно использовать аргумент –Computername. Подключение к удаленным компьютерам осуществляется не через PowerShell Remoting (WinRM), а через службу Service Manager (по аналогии с командой sc.ex).
get-service wuauserv -ComputerName remotePC1
Если вы используете PowerShell v3 или выше, то можно опросить статус службы сразу на множестве удаленных компьютерах, их имена нужно перечислить через запятую.
get-service spooler -ComputerName remotePC1,remotePC2, remotePC3| format-table Name,Status,Machinename –autosize
Командлет format-table используется в данном примере для получения более удобного табличного представления состояния служб.
Командлет Get-Service имеет еще два параметра, которые удобно использовать при администрировании служб. Параметр DependentServices получает службы, которые зависят от данной службы. Параметр RequiredServices получает службы, от которых зависит данная служба.
Приведенная ниже команда выводит список служб, требуемых службе LanmanWorkstation для запуска.
Get-Service -Name LanmanWorkstation –RequiredServices
Status Name DisplayName
—— —- ————
Running NSI Network Store Interface Service
Running MRxSmb20 SMB 2.0 MiniRedirector
Running Bowser Browser Support Driver
Следующая команда выводит зависимые службы (подробнее о настройке зависимостей служб в Windows), которым требуется служба LanmanWorkstation.
Get-Service -Name LanmanWorkstation -DependentServices
ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.
PowerShell is a great scripting tool. It not only helps save you time, it also provides greater flexibility to execute repeated tasks manually or via scheduled tasks. Almost all Windows roles and features ship with PowerShell cmdlets.
You can use Windows Operating System cmdlets, available by default, to perform operational tasks such as checking the status of a particular Windows service on multiple computers, checking the list of software installed on Windows computers, checking and collecting roles and features installed on Windows Server Operating Systems and much more.
One of the tasks Windows administrators frequently perform is checking the status of critical services on critical production servers such as Exchange Servers, SQL Servers and/or Active Directory domain controllers.
Though you can use SCCM and similar tools to provide you with a report on the status of services from a particular set of machines, SCCM requires that the SCCM Client is working on all target computers before SCCM can report on the status of services.
This is where our latest script and Server Tutorial comes in handy. You can use the PowerShell script explained in this article to quickly and easily check the status of particular services on a single or multiple Windows computers.
Checking the Status of a Single Service
If you would like to check status of a particular service on a remote computer, what you can do is execute the PowerShell command below:
Get-WMIObject -Computer -Query "Select * From Win32_Service WHERE Name Like "%SomeServiceName%"
Executing the above PowerShell command will help you get the status of a specific service specified in the “%SomeServiceName% parameter. This command connects to a remote computer specified in the “-Computer” parameter. You’ll likely want to change both the computer and service names before executing the above command.
Checking the Status of Multiple Services
In case you would like to get a list of all Windows Services that are running on a target system, execute the following PowerShell command:
Get-WMIObject Win32_Service -Computer | Where {$_.State -eq "Running"} | FT -Auto
The above command will list all Windows Services that are running from the remote computer specified in the “-Computer” parameter, and the output will be displayed in the PowerShell window. If you would like to save the output in a CSV file, adding “Export-CSV” will do the job as shown in this command:
Get-WMIObject Win32_Service -Computer | Where {$_.State -eq "Running"} | FT -Auto | Export-CSV "C:TempServicesStatus.CSV"
Checking the Status of a Single Service on Multiple Computers
While the above PowerShell commands will help you get you the status of a specific or multiple services from a single Windows computer, the following PowerShell script can be used if you would like to see the status of a single service from multiple Windows computers. All you need to do is create a text file that contains the Windows computer names and modify the script variable “$ServiceNameToCheck” to include the service you would like to check.
$ServiceNameToCheck ="SomeServiceName"
$ReportFile = "C:TempServiceStatus.CSV"
Remove-item $ReportFile -ErrorAction SilentlyContinue
$ThisSTR = "Computer Name, Service Status"
Add-Content $ReportFile $ThisSTR
$CompFile = "C:TempComputers.TXT"
Foreach ($ComputerName in Get-Content "$CompFile")
{
$Error.Clear()
Get-WMIObject -Computer $ComputerName -Query "Select * From Win32_Service WHERE Name Like "%$ServiceNameToCheck% AND {$_.State -eq "Running"}
IF ($Error.Count -ne 0)
{
$ThisSTR = $ComputerName+", Could Not Connect to Remote Computer or Service Not Running"
Add-Content $ReportFile $ThisSTR
}
else
{
$ThisSTR = $ComputerName+", Running"
Add-Content $ReportFile $ThisSTR
}
}
Write-Host "Service status was retrieved from the list of computers and the output was saved in $ReportFile"
Once the PowerShell script above has finished executing, a report file will be created named ServiceStatus.CSV in the “C:Temp” folder that contains the status of the service name specified in the “$ServiceNameToCheck” variable from all computers mentioned in the “C:TempComputers.TXT” file.
Note that the script checks to make sure the command was executed successfully before it reports the status of the service. The PowerShell script uses the “Get-WMIObject” PowerShell cmdlet to collect the status of specific service(s) from target computers. In case the Get-WMIObject is not able to connect to a target computer or if the service status is not retrieved, it will return a “Could Not Connect to Remote Computer or Service Not Running” message in the report.
Conclusion
It is quite easy to get the status of a single or multiple services from a single or multiple remote Windows computers. While there are enterprise tools available to collect an inventory from Windows computers, including the status of services, there are also cases where these PowerShell commands/scripts come in very handy, particularly when you need to quickly check the status of a particular service on multiple Windows computers.
Nirmal Sharma is a MCSEx3, MCITP and Microsoft MVP in Directory Services. He specializes in directory services, Microsoft Azure, Failover clusters, Hyper-V, System Center and Exchange Servers, and has been involved with Microsoft technologies since 1994. In his spare time, he likes to help others and share some of his knowledge by writing tips and articles on various sites and contributing to Health Packs for ADHealthProf.ITDynamicPacks.Net solutions. Nirmal can be reached at nirmal_sharma@mvps.org.
Follow ServerWatch on Twitter and on Facebook
The built-in Get-Service PowerShell cmdlet can be used to get a list of Windows services, check their statuses, filter them by name or service status. Let’s learn how to use Get-Service to check Windows services.
Syntax and Basic Usage of the Get-Service Cmdlet
The basic syntax and available parameters of the Get-Service cmdlet are as follows:
Get-Service [[-Name] <string[]>] [-ComputerName <string[]>] [-DependentServices] [-RequiredServices] [-Include <string[]>] [-Exclude <string[]>] [<CommonParameters>]
When run without parameters, the Get-Service command displays a list of all the services on the local computer and their statuses.
To check whether the specific service is running or not, specify its name or DisplayName:
Get-Service wuauserv
Or
Get-Service -DisplayName "Windows Update"
Get the status of multiple services at once:
Get-Service WSLService, WwanSvc, WlanSvc
If you don’t know the exact name of the service, you can use wildcards. For example, to list all services whose display name starts with Microsoft:
Get-Service -DisplayName Microsoft*
Use the Where-Object cmdlet to list only services with a specific state. For example, list all stopped services:
Get-Service | Where-Object {$_.status -eq 'stopped'}
Get-Service: Advanced Usage Examples
The Get-Service cmdlet returns a default property set consisting of the following properties:
- Status — Indicates the current service status. The possible values are: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused.
- Name — Displays the short name of the service
- Display Name — Show the friendly name of the service.
However, other service object properties are not displayed. You can see them all by running the command below:
Get-Service | Get-Member | Where-Object { $_.MemberType -like "*property" } | Select-Object Name, MemberType
Among these other properties, the most preferred when checking the service status is the StartType, which indicates whether the service start type is:
- Automatic — Service starts automatically during the system start-up.
- Manual — Service must be started manually by a user or application.
- AutomaticDelayedStart — service starts automatically on boot after core network services are run.
- Disabled — Service is disabled.
List services whose StartType is Automatic.
Get-Service | Where-Object { $_.StartType -eq 'Automatic' } | Select-Object Name, Status, StartType
List services that should start automatically but are not currently running:
Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' } | Select-Object Status, Name, DisplayName, StartType
Get service dependency. Such services may fail to start if their dependent services are not running:
Get-Service Dfs -RequiredServices
According to the result below, the Dfs service has six dependencies, and one is not running (Stopped), which is the RemoteRegistry.
Check Services on a Remote Computer with PowerShell
The Get-Service cmdlet retrieves the service status in the local computer by default. But it is capable of getting the service status on a remote computer.
On Windows PowerShell, the Get-Service cmdlet has a parameter called -ComputerName that accepts an array of computer names to query. This method uses the Distributed Component Object Model (DCOM) to connect to the remote machine and execute the command against it.
For example, this command retrieves the status of the services on the remote computers named DC1 and PCX.
Get-Service -Name WinRM -ComputerName DC1,PCX | Select-Object Status,Name,MachineName
On PowerShell Core (6.x+), the -ComputerName parameter has been removed from the Get-Service cmdlet because of PowerShell Core’s move away from DCOM. Instead, you must use the Invoke-Command cmdlet, which uses the WinRM to communicate to remote machines.
Invoke-Command -ComputerName DC1, PCX {Get-Service WinDefend, wuauserv | Select-Object Status, Name, DisplayName}
The Get-Service PowerShell cmdlet is an easy and powerful way to check the status of Windows services on local or remote computers. It can easily replace the old-school ways of managing services using the Services MMC snap-in (services.msc) or the sc query console command.
Cyril Kardashevsky
I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.
Начинаем серию переводов, посвященную управлению службами Windows с помощью PowerShell 2.0 и 3.0.
В данном посте будут рассмотрены следующие вопросы управления службами Windows:
- Получаем статус службы на локальном компьютере
- Получаем статус службы на удаленном компьютере
- Осуществляем фильтрацию служб (например, остановленные службы)
- Зависимые службы
Обозначим начальные условия: Вы работаете под Windows 7 и выше и у Вас имеются права администратора. Все команды рекомендуются выполнять в лабораторной или виртуальной среде, перед тем, как применять в “полевых условиях”.
ПОЛУЧАЕМ СТАТУС СЛУЖБЫ
Давайте начнем с того, что просто получим статус всех служб, запущенных на локальном компьютере. Используем для этого командлет Get-Service.
PS C:\> get-service
PowerShell, как правило, не чувствителен к регистру. Вывод приведен на скриншоте ниже.
Каждая строка представляет собой объект службы (service object).Каждый сервисный объект, как правило, имеет свои свойства. Вы можете открыть их, просто передав эти объекты в другую команду, Get-Member.
PS C:\> get-service | get-member
Результаты приведены на скриншоте ниже.
Параметр Typename сверху говорит о том, что за объект перед нами; в данном случае это System.ServiceProcess.ServiceController. На скриншоте также обведены свойства объекта. Это атрибуты, которые описывают этот тип объекта. Хотя большинство из них не используются при отображении по умолчанию, вы можете использовать их, если вы их знаете.
Например, нам интересно посмотреть информацию только о Windows Update. Через Get-Service получим информацию только о некоторых ее свойствах.
PS C:\> get-service wuauserv | select Displayname,Status,Can*
DisplayName : Windows Update
Status : Stopped
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
Как я узнал, что могу напечатать имя службы? Посмотрел с помощью Get-Service.
PS C:\> help get-service
Вы можете получить полную справочную информацию, напечатав:
PS C:\> help get-service –full
Информацию о службе можно получить по ее имени или даже начальным буквам имени.
PS C:\> get-service wi*
Status Name DisplayName
------ ---- -----------
Stopped WiaRpc Still Image Acquisition Events
Running WinDefend Windows Defender Service
Running WinHttpAutoProx... WinHTTP Web Proxy Auto-Discovery Se...
Running Winmgmt Windows Management Instrumentation
Running WinRM Windows Remote Management (WS-Manag...
Или если вам удобнее работать с отображаемыми именами, используйте параметр –Displayname.
PS C:\> get-service -DisplayName "windows a*"
Status Name DisplayName
------ ---- -----------
Stopped AllUserInstallA... Windows All-User Install Agent
Running AudioEndpointBu... Windows Audio Endpoint Builder
Running Audiosrv Windows Audio
Я должен использовать имя параметра, чтобы PowerShell воспринимал значения в качестве отображаемого имени, а не фактического имени службы. Команда будет выглядеть так:
PS C:\> get-service "windows a*"
Параметр –Name можно не печатать.
ПОЛУЧАЕМ СТАТУС СЛУЖБЫ НА УДАЛЕННЫХ КОМПЬЮТЕРАХ
До этого нас интересовало получение информации о статусе служб на локальном компьютере. Однако управление службами осуществляется на удаленных компьютерах. Если посмотреть справку по Get-Service, то можно увидеть наличие у этого командлета параметра –Computername. В данном случае подключение к удаленным компьютерам осуществляется без включения функции удаленного управления PowerShell. Если вы можете управлять службами, используя инструменты командной строки (sc.exe или консоль управления Service Manager), вы можете использовать PowerShell. Давайте взглянем на пример:
PS C:\> get-service spooler -ComputerName novo8
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
Любая команда, которую я демонстрировал, можно использовать для передачи удаленному компьютеру. Даже нескольким компьютерам, если у вас есть соответствующие права на удаленном компьютере. Если вы используете PowerShell v3, то можно легко выбрать одну службу на множестве компьютеров.
PS C:\> get-service wuauserv -ComputerName chi-dc01,chi-dc02,chi-dc03
Status Name DisplayName
------ ---- -----------
Running wuauserv Windows Update
Stopped wuauserv Windows Update
Running wuauserv Windows Update
Для наглядности представления отформатируем вывод.
PS C:\> get-service wuauserv -ComputerName chi-dc01,chi-dc02,chi-dc03 | format-table Name,Status,Machinename -autosize
Name Status MachineName
---- ------ -----------
wuauserv Running chi-dc03
wuauserv Stopped chi-dc02
wuauserv Running chi-dc01
Тот же самый результат, но в PowerShell v2.
PS C:\> 'chi-dc01','chi-dc02','chi-dc03'| foreach {get-service wuauserv -computername $_} | Format-Table Name,Status,Machinename -AutoSize
Name Status MachineName
---- ------ -----------
wuauserv Running chi-dc01
wuauserv Stopped chi-dc02
wuauserv Running chi-dc03
ОСУЩЕСТВЛЯЕМ ФИЛЬТРАЦИЮ (ИСПОЛЬЗУЯ WHERE-OBJECT)
Фильтрация служб осуществляется с помощью командлета Where-Object (where – сокращение для командлета). Все, что нам нужно от PowerShell в этом случае, так это получить только те службы, у которых статус равен “stopped”.
PS C:\> get-service | where {$_.status -eq 'stopped'}
PowerShell получает информацию обо всех службах и передает их (с помощью “|”) в следующую команду, которая осуществляет просмотр каждого объекта. Если свойство статуса объекта равно “stopped”, она остается в конвейере (pipeline), в противном случае она из него исключается. В конце выражение PowerShell отображает те объекты, которые остались в конвейере.
Результаты приведены ниже.
Теперь давайте попробуем найти одну службу на нескольких машинах. Вывод отформатируем в таблицу.
PS C:\> get-service -computername @('chi-dc01','chi-dc02','chi-dc03') | where {$_.name -eq 'wuauserv'} | format-table Name,Status,Machinename -autosize
Name Status MachineName
---- ------ -----------
wuauserv Running chi-dc02
wuauserv Running chi-dc01
wuauserv Running chi-dc03
Мы даже можем комбинировать запрос отдельных служб с их фильтрацией.
PS C:\> get-service "win*" -comp chi-dc03 | where {$_.status -eq 'running'}
Status Name DisplayName
------ ---- -----------
Running Winmgmt Windows Management Instrumentation
Running WinRM Windows Remote Management (WS-Manag...
Эта команда находит все службы на компьютере CHI-DC03, которые начинаются с ‘WIN’, но отображает только те, которые запущены.
Также можно сгруппировать объекты по свойству статуса (status property).
PS C:\> $dc03 = get-service -computername chi-dc03 | Group-Object -Property Status
Переменная $dc03 является объектом GroupInfo.
PS C:\> $dc03
Count Name Group
----- ---- -----
64 Running {System.ServiceProcess.ServiceController, Sy...
79 Stopped {System.ServiceProcess.ServiceController, Sy...
Свойство Group представляет собой коллекцию связанных служб.
PS C:\> $dc03.Get(0).group
Написанное выше проще понять, если взглянуть на скриншот.
Что касается меня, то я бы предпочел использовать хеш-таблицу.
PS C:\> $hash = get-service -computername chi-dc03 | Group-Object -Property Status -AsHashTable
PS C:\> $hash
Name Value
---- -----
Running {System.ServiceProcess.ServiceController, Sys...
Stopped {System.ServiceProcess.ServiceController, Sys...
Теперь каждое имя представляет собой свойство в хеш-таблице. Если у вас имеется опыт работы с PoweShell, вы, возможно, подумываете сделать сделующее:
PS C:\> $hash.running.count
Однако ничего не произойдет. Потому что свойство Status является просто перечислением (enumeration) для [System.ServiceProcess.ServiceControllerStatus] .NET клас и такие свойства, как Running и Stopped представляют собой целые числа. PowerShell осуществляет конвертацию, чтобы представить в более наглядной форме.
PS C:\> $hash = get-service -computername chi-dc03 | Group-Object -Property Status –AsHashTable –AsString
В чем суть параметра –AsString, на мой взгляд, достаточно очевидно. Теперь работать с хеш-таблицей стало проще.
PS C:\> $hash.running.count
62
PS C:\> $hash.running[0..3]
Status Name DisplayName
------ ---- -----------
Running ADWS Active Directory Web Services
Running AppHostSvc Application Host Helper Service
Running BFE Base Filtering Engine
Running BrokerInfrastru... Background Tasks Infrastructure Ser...
Следующей задачей на повестке дня является проверка зависимостей сервера (server dependencies).
Требуемые службы
PowerShell позволяет просто получить статус всех служб, которые требуется для данной службы, даже на удаленном компьютере.
PS C:\> get-service dns -ComputerName chi-dc03 –RequiredServices
Status Name DisplayName
------ ---- -----------
Running Afd Ancillary Function Driver for Winsock
Running Tcpip TCP/IP Protocol Driver
Running RpcSs Remote Procedure Call (RPC)
Running NTDS Active Directory Domain Services
Параметр –RequiredServices передаст объект в конвейер для каждой требуемой службы. Вы можете даже пойти дальше и проверить требуемые службы для работы данной службы.
PS C:\> get-service dns -ComputerName chi-dc03 -RequiredServices | select name,@{name="computername";expression={$_.machinename}} | get-service -RequiredServices
Status Name DisplayName
------ ---- -----------
Running RpcEptMapper RPC Endpoint Mapper
Running DcomLaunch DCOM Server Process Launcher
Параметр –Computername командлета Get-Service возьмет вывод, но только для тех объектов, у которых есть объект свойство Computername – именно поэтому я использую хеш-таблицу с Select-Object. Как мы видим проблем со службой DNS на компьютере CHI-DC03 нет.
ЗАВИСИМЫЕ СЛУЖБЫ
Мы можем сделать то же самое с зависимыми службами. Если таковых не имеется, в конвейер ничего передано не будет.
PS C:\> get-service dns -ComputerName chi-dc03 -DependentServices
PS C:\> get-service lanmanworkstation -ComputerName chi-dc03 -DependentServices
Status Name DisplayName
------ ---- -----------
Stopped SessionEnv Remote Desktop Configuration
Running Netlogon Netlogon
Running Dfs DFS Namespace
Running Browser Computer Browser
Требуемые и зависимые службы также являются частью каждого объекта службы.
PS C:\> get-service rpcss | Select *services
RequiredServices DependentServices
---------------- -----------------
{RpcEptMapper, DcomLaunch} {WwanSvc, wuauserv, WSearch, wscsvc...}
А пока Вы можете получить все зависимости для всех служб, следующая команда
PS C:\> get-service –DependentServices
Это не даст вам особо полезную информацию, поэтому я рекомендую осуществлять запрос по конкретным службам. Команда работает гораздо лучше PowerShell v3.
PS C:\> get-service dns -comp chi-dc01,chi-dc03 -RequiredServices | Sort Machinename,Name | Format-table -GroupBy machinename
Результаты видны на скриншоте ниже.
Чтобы получить подобные результаты в PowerShell v2, вам придется передать имена компьютеров (computernames) в Get-Service.
PS C:\> "chi-dc01","chi-dc03" | foreach { get-service dns -comp $_ -RequiredServices} | Sort Machinename,Name | format-table -GroupBy machinename
В следующей статье будет рассмотрен запуск, остановка и перезапуск служб.
Конец перевода.
Upd:
В посте приведены переводы статей с портала 4sysops.com
Managing Services the PowerShell way – Part 1
Managing Services the PowerShell way – Part 2
P.S. Хотим также поделиться нашей бесплатной программой для управления службами Windows – NetWrix Service Monitor. Программа отслеживает все автоматически запускаемые службы на группе серверов и в случае внезапного сбоя одной или нескольких из них отправляет уведомления по электронной почте. Функция перезапуска гарантирует, что все подконтрольные службы будут работать без простоев. Программа проста в настройке: устанавливаем, вводим имена компьютеров и указываем нужный адрес электронной почты.
In Windows, many services essential for the operation of the system and applications run in the background. Checking the status of these services is important for system administration and troubleshooting. While there are methods to check service status using the GUI, checking directly from the Command Prompt allows for quicker access to information. This article provides a detailed explanation on how to check the status of services using the Windows Command Prompt.
TOC
Commands to Check Service Status
To check the status of services from the Windows Command Prompt, you can use the sc
command or the net start
command. These commands are part of the command-line tools built into Windows and are used for service management.
Using the `sc` Command
The sc
command is used to display or change the configuration and status of services. The basic command to check the status of a service is as follows:
The service name specifies the actual name of the service. For example, to check the status of the Windows Update service, you would use the following command:
Executing this command displays details about the service, such as its name, display name, status (e.g., RUNNING, STOPPED), and service-specific error codes.
Using the `net start` Command
The net start
command is used to display a list of currently running services. Instead of directly checking the status of a specific service, it lists all services that are currently running.
Executing this command will display a list of all services that are currently running on the system. If a specific service is included in the list, it is running. If it is not included, the service is either stopped or not started.
By utilizing these commands, you can efficiently manage Windows services from the command line.
Commonly Used Service Status Check Commands
When managing or troubleshooting Windows, you may frequently need to check the status of specific services. Below are examples of commands for checking the status of commonly used services.
Windows Update Service (wuauserv)
The Windows Update service manages updates for Windows. To check the status of this service, use the following command:
Remote Desktop Service (TermService)
This service is used for accessing other computers using Remote Desktop. To check the status of this service, execute the following command:
Print Spooler Service (Spooler)
The Print Spooler service manages print jobs and sends them to the printer. To check this service, use the following command:
DHCP Client Service (Dhcp)
The DHCP service provides the function of automatically assigning IP addresses on the network. The command to check the status of this service is as follows:
Windows Firewall Service (MpsSvc)
The Windows Firewall is a service that protects the computer from unauthorized access. To check the status of this service, enter the following:
These commands allow you to easily check whether a specific service is currently running or stopped. Depending on the state of the service, appropriate actions or configuration changes can be made.
Commands to Start and Stop Services
Using the Windows Command Prompt to start or stop services is one of the basic operations in system administration. Below, we introduce commands for effectively managing services.
Commands to Start a Service
To start a service, use the net start
command or the sc start
command. You can specify the service name to start a particular service.
Or
For example, to start the Remote Desktop service, you would do the following:
Or
Commands to Stop a Service
To stop a service, use the net stop
command or the sc stop
command. You can specify the service name to stop a particular service.
Or
For example, to stop the Print Spooler service, use the following command:
Or
Commands to Restart a Service
If you need to restart a service, execute the commands to stop and then start the service in sequence. This is often necessary to apply configuration changes or solve problems.
net stop [Service Name] && net start [Service Name]
Or
sc stop [Service Name] && sc start [Service Name]
Proper use of these commandsallows for efficient system management and troubleshooting of Windows systems.
Examples of Troubleshooting with Command Prompt
This section describes common troubleshooting scenarios you might encounter while operating Windows and how you can use the Command Prompt to resolve them.
Troubleshooting a Non-Working Printer
If a printer in Windows is not working as expected, checking and, if necessary, restarting the Print Spooler service can resolve the issue.
- Check the status of the Print Spooler service:
sc query Spooler
. If the status is not “RUNNING,” the service may be stopped. - Restart the Print Spooler service:
net stop Spooler && net start Spooler
This command stops and then restarts the Print Spooler service, which can resolve temporary issues related to the printer.
Solving Internet Connection Issues
If there are issues with the internet connection, checking and restarting the DHCP Client service to attempt reassignment of the IP address can be effective.
- Check the status of the DHCP Client service:
sc query Dhcp
. If the service is stopped, it may not be assigning IP addresses correctly. - Restart the DHCP Client service:
net stop Dhcp && net start Dhcp
This action can prompt the system to acquire a new IP address from the DHCP server, potentially resolving connection issues.
Conclusion
Using the Command Prompt to manage Windows services is a powerful skill for system administrators and advanced users. Understanding how to check the status, start, stop, and restart services enables quick resolution of many common issues. The commands introduced in this article serve as a foundation for operating and troubleshooting Windows, and can greatly aid in efficient system management. Make use of these commands to enhance your system administration capabilities.