В Windows вы можете управлять службами не только из графической консоли services.msc или утилиты командной строки Sc.exe (первоначальна включалась в пакет ресурсов Resource Kit), но и с помощью PowerShell. В этой статье мы смотрим различные сценарии управления службами Windows с помощью PowerShell.
Содержание:
- Основные командлеты PowerShell для управления службами Windows
- Остановка, запуск, приостановка и перезапуск служб из PowerShell
- Set-Service – изменение настроек службы Windows
- Создание и удаление служб Windows c помощью PowerShell
- Изменение учетной записи для запуска службы
Основные командлеты PowerShell для управления службами Windows
Существует восемь основных командлетов Service, предназначенных для просмотра состояния и управления службами Windows.
Чтобы получить весь список командлетов Service, введите команду:
Get-Help \*-Service
- Get-Service — позволяет получить службы на локальном или удаленном компьютере, как запущенные, так и остановленные;
- New-Service – создать службу. Создает в реестре и базе данных служб новую запись для службы Windows;
- Restart-Service – перезапустить службу. Передает сообщение об перезапуске службы через Windows Service Controller
- Resume-Service – возобновить службы. Отсылает сообщение о возобновлении работы диспетчеру служб Windows;
- Set-Service — изменить параметры локальной или удаленной службы, включая состояние, описание, отображаемое имя и режим запуска. Этот командлет также можно использовать для запуска, остановки или приостановки службы;
- Start-Service – запустить службу;
- Stop-Service – остановить службу (отсылает сообщение об остановке диспетчеру служб Windows);
- Suspend-Service приостановить службу. Приостановленная служба по-прежнему выполняется, однако ее работа прекращается до возобновления работы службы, например с помощью командлета Resume-Service.
Получить подробное описание и примеры использования конкретного командлета можно через Get-help:
Get-Help Start-Service
Get-Service: получаем список служб и их состояние
Получить список и состояние (Running/Stopped) службы на локальном или удаленном компьютере можно с помощью командлета Get-Service. Параметр -Name позволяет делать отбор по имени службы. Имя службы можно задать с использованием подстановочного символа *.
Если вы не знаете точное имя службы, есть возможность найти службы по отображаемому имени с помощью параметра –DisplayName. Можно использовать список значений и подстановочные знаки.
.
Командлет Get-Service можно использовать для получения состояния служб на удаленных компьютерах, указав параметр -ComputerName. Можно опросить статус службы сразу на множестве удаленных компьютеров, их имена нужно перечислить через запятую. Например, приведенная ниже команда получает состояние службы Spooler на удаленных компьютерах RM1 и RM2.
Get-Service spooler –ComputerName RM1,RM2
Status Name DisplayName ------ ---- ----------- Running spooler Print Spooler Stopped spooler Print Spooler
Вывести все свойства службы позволит командлет Select-Object:
Get-Service spooler | Select-Object *
Командлет Select-Object позволит вывести определенные свойства службы. Например, нам нужно вывести имя, статус и доступные возможности службы Spooler:
Get-Service Spooler | Select DisplayName,Status,ServiceName,Can*
Командлет Get-Service имеет два параметра, которые позволяют получить зависимости служб:
- Параметр -DependentServices позволяет вывести службы, которые зависят от данной службы;
- Параметр -RequiredServices позволяет вывести службы, от которых зависит данная служба.
Приведенная ниже команда выводит службы, необходимые для запуска службе Spooler:
Get-Service –Name Spooler -RequiredServices
Следующая команда выводит службы, которые зависят от службы Spooler:
Get-Service –Name Spooler -DependentServices
При необходимости найти службы с определенным состоянием или параметрами, используйте командлет Where-Object. Например, получим список запущенных служб со статусом Running:
Get-Service | Where-Object {$_.status -eq 'running'}
Для вывода служб с типом запуска Manual, выполните команду
Get-Service | Where-Object {$_.starttype -eq 'Manual'}
Проверить, что в системе имеется указанная служба:
if (Get-Service "ServiceTest" -ErrorAction SilentlyContinue)
{
Write-host "ServiceTest exists"
}
Остановка, запуск, приостановка и перезапуск служб из PowerShell
Остановить службу можно с помощью командлета Stop-Service. Чтобы остановить службу печати, выполните команду:
Stop-Service -Name spooler
Командлет Stop-Service не выводит никаких данных после выполнения. Чтобы увидеть результат выполнения команды, используйте параметр -PassThru.
Обратите внимание, что не каждую службу можно остановить. Если есть зависимые службы, то получите ошибку
Cannot stop service because it has dependent services. It can only be stopped if force flag set.
Для принудительной остановки используйте параметр –Force. Вы должны помнить, что остановятся также все зависимые службы:
Stop-Service samss –Force -Passthru
Следующая команда остановит перечисленные службы (bits,spooler) со статусом ”Running”:
get-service bits,spooler | where {$_.status -eq 'running'} | stop-service –passthru
Командлет Start-Service запускает остановленные службы:
Start-Service -Name spooler -PassThru
Служба не запустится, если есть остановленные зависимые службы. Чтобы их найти и включить:
get-service samss | Foreach { start-service $_.name -passthru; start-service $_.DependentServices -passthru}
Командлет Suspend-Service может приостанавливать службы, допускающие временную приостановку и возобновление. Для получения сведений о возможности временной приостановки конкретной службы используйте командлет Get-Service со свойством «CanPauseAndContinue«.
Get-Service samss | Format-List name, canpauseandcontinue
Чтобы отобразить список всех служб, работа которых может быть приостановлена, введите команду:
Get-Service | Where-Object {$_.canpauseandcontinue -eq "True"}
Приостановим службу SQLBrowser:
Suspend-Service -Name SQLBrowser
Для возобновления работы приостановленной службы служит командлет Resume-service:
Resume-Service -Name SQLBrowser
Следующая команда возобновляет работу всех приостановленных служб:
get-service | where-object {$_.Status -eq "Paused"} | resume-service
Командлет Restart-Service перезапускает службу:
Restart-Service -Name spooler
Эта команда запускает все остановленные сетевые службы компьютера:
get-service net* | where-object {$_.Status -eq "Stopped"} | restart-service
Параметр —ComputerName у этих командлетов отсутствует, но их можно выполнить на удаленном компьютере с помощью командлета Invoke-Command или через пайп:
Например, чтобы перезапустите очередь печати на удаленном компьютере RM1, выполните команду:
Get-Service Spooler -ComputerName RM1 | Start-Service
Set-Service – изменение настроек службы Windows
Командлет Set-Service позволяет изменить параметры или настройки служб на локальном или удаленном компьютере. Так как состояние службы является свойством, этот командлет можно использовать для запуска, остановки и приостановки службы. Командлет Set-Service имеет параметр -StartupType, позволяющий изменять тип запуска службы.
Изменим тип запуска службы spooler на автоматический:
Set-Service spooler –startuptype automatic –passthru
Можно перевести службу на ручной (manual) запуск:
Set-Service spooler –startuptype manual –passthru
Создание и удаление служб Windows c помощью PowerShell
New-Service – командлет для создания новой службы в Windows. Для новой службы требуется указать имя и исполняемый файл (вы можете запустить PowerShell скрипт как службу Windows).
В примере создадим новую службу с именем TestService.
new-service -name TestService -binaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
С помощью параметра Get-WmiObject получим информацию о режиме запуска и описание службы
get-wmiobject win32_service -filter "name='testservice'"
Изменить параметры новой службы можно командой
Set-Service -Name TestService -Description ‘My Service’ -StartupType Manual
Чтобы удалить службу используйте команду
(Get-WmiObject win32_service -Filter ″name=′TestService′″).delete()
Изменение учетной записи для запуска службы
Вы можете изменить учетную запись, из-под которой запускается служба. Получим имя учетной записи, которая используется для запуска службы TestService
get-wmiobject win32_service -filter "name='TestService'" | Select name,startname
Для изменения имени и пароля учетной записи выполняем команды.
$svc = get-wmiobject win32_service -filter "name='TestService'"
$svc.GetMethodParameters("change")
В результате получаем список параметров метода Change(). Считаем на каком месте находятся параметры StartName и StartPassword – 20 и 21 место соответственно.
$svc | Invoke-WmiMethod -Name Change –ArgumentList @ ($null,$null,$null,$null,$null,$null,$null, $null,$null,$null,$null,$null,$null,$null,$null,$null, $null,$null,$null,"Administrator","P@ssw0rd")
Либо вы можете указать имя gMSA аккаунта. Пароль при этом не указывается.
Как видите, PowerShell позволяет легко управлять службами Windows. Можно создавать, останавливать, запускать и возобновлять службы, менять их свойства. Большинство командлетов позволяют управлять службами на удаленных компьютерах.
Время на прочтение8 мин
Количество просмотров116K
Продолжаем знакомиться с тем, как осуществлять управление службами Windows с использованием PowerShell. В предыдущем посте мы рассмотрели, как получить статус службы на локальном и удаленном компьютере, произвести фильтрацию служб (например, найти только остановленные службы) и определить зависимые службы. В этом посте будут рассмотрены такие достаточно тривиальные вещи, как:
- Остановка службы
- Запуск службы
- Перезапуск службы
- Приостановка и возобновление работы
- Управление удаленными службами
- Настраиваем автозагрузку службы
Мы уделим большее внимание разбору команд в PowerShell для осуществления выше перечисленного на локальном компьютере. В разделе “управление службами удаленных компьютерах” мы рассмотрим, ограничения работы в PowerShell v2 и v3. Подробности под катом.
Предыдущая статья:
Управляем службами Windows с помощью PowerShell. Часть 1. Получаем статус служб
PS C:\> get-service bits
Status Name DisplayName
------ ---- -----------
Running bits Background Intelligent Transfer Ser...
Так как команда для получения статуса службы называется Get-Service, догадаться о том, как пишутся другие команды не составит труда. На худой конец мы можем спросить у PowerShell обо всех командах, так или иначе относящихся к работе со службами. Обратите внимание, что мы использовали параметр –noun для получения всех команд, связанных со службами.
Взглянем на эти команды внимательнее.
STOP-SERVICE
Чтобы остановить службу, мы должны уточнить ее имя.
PS C:\> stop-service wuauserv
Однако в конвейер ничего не будет передано. Некоторые командлеты, такие как Stop-Service, созданы таким образом, что по умолчанию они не записывают объект в конвейер. Мы же заставим это сделать, использовав параметр –Passthru.
PS C:\> stop-service bits -PassThru
Status Name DisplayName
------ ---- -----------
Stopped bits Background Intelligent Transfer Ser...
Если служба не запущена, то командлет ничего не выведет, равно как и не выдаст никакой ошибки. Поэтому иногда лучше передать объект в Stop-Service (естественно использовав при этом параметр –whatif).
PS C:\> get-service browser | stop-service -WhatIf
What if: Performing operation “Stop-Service” on Target “Computer Browser (browser)”.
Параметр –WhatIf был добавлен для того, чтобы мы посмотрели, что будет, если командлет будет запущен. Когда я удостоверюсь, что это именно та служба, которая меня интересует, я просто удалю -Whatif и остановлю службу.
PS C:\> get-service browser | stop-service
Как я уже упомянул выше, если служба уже остановлена, то командлет ничего не сделает. И использование Stop-Service в этом случае никому не навредит. Однако я все же предпочитают более цивилизованный подход, а именно:
PS C:\> get-service bits | where {$_.status -eq 'running'} | stop-service -pass
Status Name DisplayName
------ ---- -----------
Stopped bits Background Intelligent Transfer Ser...
Если служба запущена, то объект передается в конвейер и отправляется в Stop-Service. Ниже приведен вариант с остановкой нескольких служб.
PS C:\> get-service bits,wsearch,winrm,spooler | where {$_.status -eq 'running'} | stop-service -whatif
What if: Performing operation "Stop-Service" on Target "Print Spooler (spooler)".
What if: Performing operation "Stop-Service" on Target "Windows Remote Management (WS-Management) (winrm)".
What if: Performing operation "Stop-Service" on Target "Windows Search (wsearch)".
Некоторые службы не захотят останавливаться – в силу наличия зависимых служб – что мы и видим на скриншоте ниже.
В таком случае используем параметр –Force. В большинстве случаев это работает, но без “защиты от дурака”. Помните, что команда также остановит зависимые службы.
PS C:\> stop-service lanmanserver -force –PassThru
Status Name DisplayName
------ ---- -----------
Stopped Browser Computer Browser
Stopped lanmanserver Server
START-SERVICE
Запуск службы осуществляется аналогичным образом. Он поддерживает параметр –Whatif, и вам придется использовать –Passthru, чтобы увидеть объекты.
PS C:\> start-service wuauserv -PassThru
Status Name DisplayName
------ ---- -----------
Running wuauserv Windows Update
И снова: если служба уже запущена, командлет ничего не сделает. Однако вы можете попытаться запустить службу и получите такую ошибку.
Причиной тому в большинстве случаев является выключенные службы. Как конфигурировать настройки службы, я расскажу в следующей статье.
Если вы хотите запустить службы и все службы, зависимые от нее, используйте следующее выражение:
PS C:\> get-service lanmanserver | Foreach { start-service $_.name -passthru; start-service $_.DependentServices -passthru}
Status Name DisplayName
------ ---- -----------
Running lanmanserver Server
Running Browser Computer Browser
Мы должны явно получить зависимые службы, потому что Start-Service не запустит автоматически их.
RESTART-SERVICE
Вы удивитесь, но перезапуск службы работает также как два предыдущих примера. Используйте –Passthru, если хотите убедиться, что служба запущена.
PS C:\> restart-service spooler -PassThru
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
Так как мы осуществляем остановку службы, нам может понадобиться параметр –Force.
ПРИОСТАНОВКА И ВОЗОБНОВЛЕНИЕ РАБОТЫ
Работа некоторых служб может быть приостановлена на некоторое время, а затем возобновлена, и мы можем это сделать через PowerShell. Однако если служба не удовлетворяет требованиям, мы получим такие ошибки. (на примере показано, что мы пытались приостановить службу bits)
В чем же проблема? Смотрим на объект (используя Get-Service).
PS C:\> get-service bits | select *
Name : bits
RequiredServices : {RpcSs, EventSystem}
CanPauseAndContinue : False
CanShutdown : False
CanStop : True
DisplayName : Background Intelligent Transfer Service
DependentServices : {}
MachineName : .
ServiceName : bits
ServicesDependedOn : {RpcSs, EventSystem}
ServiceHandle : SafeServiceHandle
Status : Running
ServiceType : Win32ShareProcess
Site :
Container :
Если значение свойства CanPauseAndContinue равно True, значит мы можем приостанавливать и возобновлять работу службы. Найдем такие службы:
PS C:\> get-service | where {$_.CanPauseandContinue}
Status Name DisplayName
------ ---- -----------
Running LanmanServer Server
Running LanmanWorkstation Workstation
Running MSSQLSERVER SQL Server (MSSQLSERVER)
Running O2FLASH O2FLASH
Running stisvc Windows Image Acquisition (WIA)
Running Winmgmt Windows Management Instrumentation
Как мы видим, не так много служб удовлетворяют этому требованию.
PS C:\> suspend-service o2flash -PassThru
Status Name DisplayName
------ ---- -----------
Paused O2FLASH o2flash
Готовы возобновить работу службы? Используйте следующее выражение:
PS C:\> resume-service o2flash -PassThru
Status Name DisplayName
------ ---- -----------
Running O2FLASH o2flash
Оба командлета также поддерживают –Whatif.
УДАЛЕННЫЕ СЛУЖБЫ
Как вы могли обратить внимание, все примере выше мы демонстрировали на локальном машине. И это неслучайно. К сожалению даже в PowerShell v3, ни у одного из этих командлетов нет параметра, который позволял бы управлять службой на удаленном компьютере. Get-Service, конечно, поддерживает параметр –Computername, но не более. Службу лицезреть вы сможете, а что-либо с ней сделать не получится. Нет, можно, конечно, если удаленный компьютер работает с PS v2 и включен PowerShell Remoting. Тогда мы можете использовать все выше приведенные команды, используя Invoke-Command для удаленного компьютера или PSSession. С другой стороны, проще управлять одной службой на нескольких серверах.
PS C:\> Invoke-Command {restart-service dns –passthru} –comp chi-dc03,chi-dc02,chi-dc01
Управление службами на удаленных компьютерах не ограничивается вышеперечисленным, но это уже будет предмет рассмотрения последующих статей.
Все эти командлеты могут быть использованы в конвейерном выражении и зачастую это лучший вариант. Использование Get-Service для получения объектов и последующая передача их в подходящий командлет.
УСТАНАВЛИВАЕМ УДАЛЕННЫЙ СТАТУС
Итак, мы выяснили, что у командлета Stop-Service отсутствует такой полезный параметр как –Computername. Мы можете использовать эти команды в удаленной сессии, обратившись к командлету Invoke-Command, что уже само по себе продуктивно, если вы работаете со службой на нескольких компьютерах. Одно можно запускать, останавливать, перезапускать, ставить на паузу и запускать заново, используя Set-Service.
PS C:\> set-service wuauserv -ComputerName chi-dc03 -Status stopped -WhatIf
What if: Performing operation "Set-Service" on Target "Windows Update (wuauserv)".
Эта команда поддерживает параметр –WhatIf. Вы также должны использовать –Passthru для передачи объектов в конвейер.
PS C:\> set-service bits -ComputerName chi-dc03 -Status running -PassThru
Status Name DisplayName
------ ---- -----------
Running bits Background Intelligent Transfer Ser...
Валидными значениям для параметра –Status являются “запущена” (running), “остановлена” (stopped) и “на паузе” (paused). Помните, что у службы есть зависимые службы, мы не сможете изменять ее, что и продемонстрировано на скриншоте ниже.
К сожалению, у Set-Service отсутствует параметр –Force, поэтому придется вернуться к использованию PowerShell remoting и Invoke-Command. Если вы хотите перезапустить удаленную службу, используйте следующую команду:
PS C:\> set-service w32time -ComputerName chi-dc03 -Status Stopped -PassThru | set-service -PassThru -Status Running
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
Не забудьте использовать –Passthru, в противном случае вторая команда Set-Service ничего не осуществит.
Что по мне, так я предпочитаю работать сразу с несколькими службами, которые я не могу удаленно остановить, используя Set-Service, хотя их запуск проблем составляет. Я использую Invoke-Command. Но помните, что используя параметр –Computername PowerShell осуществляет подключение, используя RPC и DCOM, что может привести к проблемам с файрволом. Invoke-Command использует PowerShell remoting, который мы может быть еще не настроили или не включили.
УСТАНАВЛИВАЕМ ТИП АВТОЗАПУСКА СЛУЖБЫ
Set-Service полезнен, когда вы хотите включить или отключить службу, используя параметр –StartupType. Если Вы настроили службу, используя значения Automatic, Manual or Disabled. К сожалению, не существует варианта для Automatic (Delayed).
PS C:\> set-service remoteregistry -StartupType Manual -WhatIf
What if: Performing operation "Set-Service" on Target "Remote Registry (remoteregistry)".
PS C:\> set-service remoteregistry -StartupType Manual -PassThru
Status Name DisplayName
------ ---- -----------
Stopped remoteregistry Remote Registry
Однако, просто взглянув на объект, мы не сможем сказать, к какому типу автозагрузки он относится.
PS C:\> get-service remoteregistry | select *
Name : remoteregistry
RequiredServices : {RPCSS}
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
DisplayName : Remote Registry
DependentServices : {}
MachineName : .
ServiceName : remoteregistry
ServicesDependedOn : {RPCSS}
ServiceHandle : SafeServiceHandle
Status : Stopped
ServiceType : Win32ShareProcess
Site :
Container :
Как это сделать – одна из тем следующей статьи.
Помните, что изменение типа автозагрузки не повлияет на текущий статус службы.
PS C:\> set-service remoteregistry -StartupType Disabled -PassThru
Status Name DisplayName
------ ---- -----------
Running remoteregistry Remote Registry
Так что если вы хотите выключить и остановить (или включить и запустить) службу, передайте объект в подходящий командлет.
PS C:\> set-service remoteregistry -StartupType Disabled -PassThru | Stop-Service -PassThru
Status Name DisplayName
------ ---- -----------
Stopped remoteregistry Remote Registry
Технически, Set-Service позволяет вам изменить отображаемое имя службы и описание, но лично мне никогда не приходилось использовать в своей работе. Я использую Set-Service для включения и выключения служб. Если необходимо управлять службами удаленно, то я использую Invoke-Command.
Все, что я продемонстрировал в последних статьях, было связано с использованием специфических типов объектов службы, которые, как вы могли заметить, имеют некоторые ограничения. В следующей статье мы рассмотрим другие возможности по управлению службами, которые призваны обойти эти ограничения.
Upd:
В посте приведены переводы статей с портала 4sysops.com
Managing Services the PowerShell way – Part 3
Managing Services the PowerShell way – Part 4
In this tutorial, I will explain how to restart a Windows service using PowerShell. As a system administrator for a company, I recently had an issue where I needed to restart a critical service on one of our servers located in New York.
PowerShell provides a built-in cmdlet called Restart-Service
that allows you to restart a Windows service. The Restart-Service cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. This cmdlet can be used to restart services on both local and remote computers.
Restart a Service on the Local Computer using PowerShell
To restart a service on the local computer, follow these steps:
- Open PowerShell as an administrator.
- Use the
Get-Service
cmdlet to retrieve the service you want to restart. For example, if you want to restart the “Print Spooler” service, run the following command:
Get-Service -Name 'Spooler'
This command will display information about the “Print Spooler” service, including its current status.
- To restart the service, use the
Restart-Service
cmdlet followed by the service name:
Restart-Service -Name 'Spooler'
PowerShell will attempt to stop and then start the “Print Spooler” service.
- Verify that the service has been successfully restarted by running
Get-Service
again:
Get-Service -Name 'Spooler'
The output should show that the service is now running.
Check out Install Git on Windows Using PowerShell
Restart a Service on a Remote Computer using PowerShell
To restart a service on a remote computer, you need to use the -ComputerName
parameter with the Restart-Service
cmdlet. Here’s an example:
- Open PowerShell as an administrator.
- To restart a service on a remote computer, use the following command:
Restart-Service -Name 'Spooler' -ComputerName 'NYC-PrintServer01'
Replace 'Spooler'
with the name of the service you want to restart and 'NYC-PrintServer01'
with the name or IP address of the remote computer.
- PowerShell will attempt to connect to the remote computer, stop the specified service, and then start it again.
- To verify that the service has been successfully restarted on the remote computer, use the following command:
Get-Service -Name 'Spooler' -ComputerName 'NYC-PrintServer01'
The output should confirm that the service is now running on the remote computer.
Check out Monitor and Manage CPU Usage using Windows PowerShell
Restart Multiple Services using PowerShell
If you need to restart multiple services at once, you can use the Get-Service
cmdlet with the -DisplayName
parameter to retrieve services based on a partial name match. Here’s an example:
- Open PowerShell as an administrator.
- To restart all services that contain the word “SQL” in their display name, use the following command:
Get-Service -DisplayName '*SQL*' | Restart-Service
This command retrieves all services with “SQL” in their display name and pipes them to the Restart-Service
cmdlet, which restarts each service one by one.
- To verify that the services have been successfully restarted, use the following command:
Get-Service -DisplayName '*SQL*'
The output should show that all the matching services are now running.
Check out Disable Windows Defender Using PowerShell
Handle Services That Cannot Be Restarted
In some cases, you may encounter services that cannot be restarted due to dependencies or other issues. To handle such scenarios, you can use the -Force
parameter with the Restart-Service
cmdlet. The -Force
parameter attempts to stop the service and all its dependent services before restarting them. Here’s an example:
- Open PowerShell as an administrator.
- To forcefully restart a service named “Windows Search” and its dependencies, use the following command:
Restart-Service -Name 'WSearch' -Force
This command will attempt to stop the “Windows Search” service and its dependent services, and then start them again.
- Verify that the service and its dependencies have been successfully restarted by running:
Get-Service -Name 'WSearch'
The output should indicate that the service is now running.
Conclusion
In this tutorial, I explained how to restart Windows services using PowerShell using the Restart-Service
cmdlet. I explained how to restart a service on a local computer or a remote computer using PowerShell. I have also explained how to restart multiple services using PowerShell.
You may also like:
- Install Snipping Tool in Windows 11 Using PowerShell
- Get an IP Address Using PowerShell in Windows
- Set Service to Automatic Using PowerShell
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.
To restart a service using PowerShell, you can use the `Restart-Service` cmdlet followed by the service name to quickly and effectively restart the specified service.
Here’s a code snippet:
Restart-Service -Name 'YourServiceName'
Understanding Windows Services
What is a Windows Service?
A Windows Service is a specialized type of application that operates in the background and does not require user interaction. Services are crucial for maintaining the operational integrity of the Windows operating system, as they manage various tasks like handling network requests, managing hardware processes, and even running scheduled tasks. Unlike standard applications, which run in user sessions, Windows Services can run without a user being logged into the system.
Importance of Restarting Services
Restarting services is often necessary for a variety of reasons:
- Performance Issues: Over time, services can consume more memory or CPU resources, which may lead to degraded performance.
- Updates and Configuration Changes: After installing updates or changing configuration settings, a service may need to be restarted for the changes to take effect.
- Error Recovery: Services may occasionally hang or become unresponsive. Restarting them can restore normal functionality.
PowerShell Restart Service Remote: A Quick Guide
PowerShell Basics for Service Management
Introduction to PowerShell
PowerShell is a task automation framework that includes a command-line shell and a scripting language, primarily designed for system administration. It enables administrators to perform various tasks through cmdlets, which are specialized .NET classes.
Cmdlet Overview
When managing Windows Services through PowerShell, a few cmdlets are frequently utilized:
- `Get-Service`: Retrieves the status of services on the system.
- `Start-Service`: Starts a stopped service.
- `Stop-Service`: Stops a running service.
- `Restart-Service`: The focus of this article; it stops a running service and then starts it again.
PowerShell Restart Server: A Quick How-To Guide
Restarting Services with PowerShell
The `Restart-Service` Cmdlet
The `Restart-Service` cmdlet is designed to stop and then start a Windows service in a single command. Its syntax is straightforward:
Restart-Service -Name "ServiceName"
This command requires the service’s name as a parameter, and it’s important to use the exact name of the service as it appears in the Services management console.
Basic Usage of Restart-Service
To restart a service using PowerShell, the command can be quite simple. For example, if you want to restart the Windows Update service, you would use:
Restart-Service -Name "wuauserv"
This command sends a stop signal to the Windows Update service, and once it has stopped, it automatically issues a start signal. Understanding how this cmdlet works can help you effectively manage services without needing deep technical knowledge.
Restarting a Service with Options
Using the `Force` Parameter
In some cases, you may need to forcibly restart a service, especially if it is not responding to a standard stop request. The `-Force` flag can be added to the command:
Restart-Service -Name "Spooler" -Force
By using this parameter, you instruct PowerShell to disregard the service status and simply restart it, which can be useful in recovering hung services.
Using the `Delay` Parameter
If you would like to introduce a delay before restarting a service, the `-Delay` option allows for this control:
Restart-Service -Name "bits" -Delay 10
In this example, PowerShell will wait for 10 seconds after stopping the Background Intelligent Transfer Service before starting it again. This can help ensure that the service has completely stopped before it attempts to start again.
PowerShell Start Services: A Quick Guide to Getting Started
Advanced Techniques
Restarting Multiple Services
PowerShell excels at handling multiple items simultaneously. To restart more than one service at once, you can utilize a pipeline approach with the `ForEach-Object` cmdlet:
"Service1", "Service2" | ForEach-Object { Restart-Service -Name $_ }
This command effectively restarts each service specified in the list. It illustrates the power of PowerShell’s ability to handle collections of objects efficiently.
Checking Service Status Before Restarting
Before you attempt to restart a service, it is prudent to check its status. You can utilize the `Get-Service` cmdlet alongside a conditional statement:
$service = Get-Service -Name "MSSQLSERVER"
if ($service.Status -eq 'Running') { Restart-Service -Name "MSSQLSERVER" }
In this example, the script checks if the SQL Server service is running. If it is, then the command will proceed to restart it. This extra step can prevent unnecessary errors.
Creating a PowerShell Script to Restart a Service
Building a PowerShell script to automate the service restart process can save time and ensure consistency. Here’s how you can create a simple script:
param (
[string]$ServiceName
)
$service = Get-Service -Name $ServiceName
if ($service.Status -eq 'Running') {
Restart-Service -Name $ServiceName
} else {
Write-Output "Service $ServiceName is not running."
}
This script accepts the service name as a parameter, checks if it’s running, and then restarts it if necessary. If the service isn’t running, it outputs a user-friendly message. This approach allows you flexibility and reusability in service management.
PowerShell Restart Process: Simple Steps to Master It
Troubleshooting Common Issues
Error Handling in PowerShell
When executing service restart commands, you may encounter various errors, such as permission issues or service dependency failures. Implementing error handling using try-catch blocks can provide more control:
try {
Restart-Service -Name "SomeService"
} catch {
Write-Output "Failed to restart service: $_"
}
This mechanism captures any error generated by the command and displays a helpful message, allowing for easier troubleshooting.
Logging and Monitoring Service Restarts
To maintain oversight of service management actions, it’s useful to implement logging. You can log restart actions to a file for later review:
Restart-Service -Name "ServiceName" -Verbose | Out-File "C:\Logs\ServiceRestart.log" -Append
In the above command, the `-Verbose` switch provides detailed output which is then appended to a log file. This practice offers insight into your service management operations.
PowerShell: Start Service on Remote Computer Easily
Best Practices
Timing Considerations
When scheduling service restarts, it’s best to consider timing. Performing restarts during off-peak hours can minimize impact on users and ensure that the services are restarted when they are least likely to be needed.
Automation Tips
To further streamline service management, consider using Task Scheduler in Windows to automate PowerShell scripts. By scheduling a script to run at specific intervals or events, you can ensure services are maintained without manual intervention, ultimately improving system reliability.
Mastering PowerShell Get Service: Quick Tips and Tricks
Conclusion
Utilizing PowerShell for managing Windows services, particularly the `Restart-Service` cmdlet, offers immense flexibility and efficiency. With a solid grasp of these commands and best practices, you can ensure a smoother operation of services within your environment, leading to improved performance and reduced downtime. Experimenting with these commands not only enhances your skills but also fosters a deeper understanding of the Windows operating system’s service management capabilities.
Windows PowerShell Restart-Service
The most efficient way for PowerShell to cure a hung service is with the verb ‘restart’. Restart-Service xyz is just simpler and more efficient than stop-Service xyz, followed by start-Service xyz. If you are new to PowerShell Restart-Service, then I suggest that you begin with my Get-Service page.
Topics for PowerShell Restart-Service
- Example 1: How to Restart a Service
- Example 2: Avoid the Trap of Name or DisplayName
- Example 3: How to Simply Start a Windows Service
- Example 4: How to Stop a Service
♣
Example 1: How to Restart a Service
The service which benefits most from Restart-Service is, «Spooler». The reason being the printer gives more trouble than any other piece of hardware, and often restarting the Spooler cures the problem. The inferior, but ruthless method of curing such printer jams is to reboot the computer. When the computer is also a fileserver, this technique is undesirable.
Production Script
All you really need is this simple command:
# PowerShell Restart-Service example
Restart-Service «Spooler»
Note 1: You can change «Spooler» to the name of another service. To list services see PowerShell’s Get-Service
Comprehensive Restart-Service Script
# PowerShell cmdlet to restart the Spooler service
Clear-Host
$SrvName = «Spooler»
$ServicePrior = Get-Service $SrvName
«$srvName is » + $servicePrior.status
Set-Service $SrvName -startuptype manual
Restart-Service $srvName
$ServiceAfter = Get-Service $SrvName
«$SrvName is now » + $ServiceAfter.status
Set-Service $SrvName -startuptype automatic
Learning Points
Note 2: My biggest fear is that in a production script I will misspell the name of the service. Thus, check for success by observing this system message:
WARNING: Waiting for service ‘Print Spooler (Spooler)’ to finish starting…
Note 3: There will be variations depending on which operating system you are using.
Guy Recommends: A Free Trial of the Network Performance Monitor (NPM) v11.5
SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network. This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.
What I like best is the way NPM suggests solutions to network problems. Its also has the ability to monitor the health of individual VMware virtual machines. If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.
Download a free trial of Solarwinds’ Network Performance Monitor
Example 2: Avoid the Trap of Name or DisplayName
What’s in a Name? What do these groups of services have in common?
Group A
Alerter, Messenger, WebClient
Group B
Print Spooler, Telnet, Telephony and Windows Time
More importantly, why won’t the PowerShell’s service family interact with Group B?
The Answer: Some services have a ‘Display Name’ which differs from their ‘Service Name’, for example Telnet and Tlnsvr. How did I find this out? When I tried to start ‘Telnet’, or ‘Print Spooler’, nothing happened. Yet if I had a manual walk-through in the Service GUI, no problem. Then I ran Get-Service * and observed the two columns, Name and also Display Name. What threw me into confusion was Group A, where both names are the same.
Just to emphasise, if you wish to use the name ‘Print Spooler’, you need to specify the property -DisplayName.
# PowerShell Restart-Service example using displayName
Restart-Service -displayName «Print Spooler»
Note 4: You could research the names and displayNames with Get-Service.
Example 3: How to Simply Start a Windows Service
In Windows Server 2003 days I choose the Alerter service for testing, partly because it’s relatively harmless service, and partly because its name is near the top of the list! However, since it’s been removed from Windows 7 and Server 2008 does I have chosen PLA (Performance Logs and Alerts) to test PowerShell’s service cmdlets.
Preliminary Script
Let us check the service’s status, and also let us ‘warm up’ with Get-Service before we employ other members of the service family.
# PowerShell cmdlet to check a service’s status
$srvName = «PLA»
$servicePrior = Get-Service $srvName
$srvName + » is now » + $servicePrior.status
Learning Points
Note 5: I have decided to introduce the variable $srvName to hold the value of the service. Hopefully this will emphasise the name of the service, and prompt you to change it as necessary for your project.
Note 6: Observe how I mix the ”literal phrases” with the $variables and properties to produce a meaningful output.
Guy Recommends: SolarWinds Free Wake-On-LAN Utility
Encouraging computers to sleep when they’re not in use is a great idea – until you are away from your desk and need a file on that remote sleeping machine!
WOL also has business uses for example, rousing machines so that they can have update patches applied. My real reason for recommending you download this free tool is because it’s so much fun sending those ‘Magic Packets’. Give WOL a try – it’s free.
Download your free copy of SolarWinds Wake-On-LAN
The Main Event – Starting PLA
Windows 7 and Server 2008 (and later) do not have an Alerter service, this is why I now use PLA (Performance Logs and Alerts) to test PowerShell’s start-Service.
# PowerShell cmdlet to start a named service
$srvName = «PLA»
$servicePrior = Get-Service $srvName
«$srvName is now » + $servicePrior.status
Set-Service $srvName -startuptype manual
Start-Service $srvName
$serviceAfter = Get-Service $srvName
«$srvName is now » + $serviceAfter.status
Learning Points
Note 7: Observe how the speech marks are slightly different in this script compared with the previous:
«$srvName is now » + $servicePrior.status
compared with
$srvName + » is now » + $servicePrior.status
My points are:
a) Experiment yourself.
b) To some extent, these learning scripts leave traces of my thinking process.
Note 8: I prepared the above script to help you appreciate the factors needed to control a Windows Service. It also reflects my thinking process of how I learn about a command. On the other hand, for a production script you could take a much more ruthless approach and simplify the script thus:
Set-Service PLA -startuptype manual
Start-Service PLA
Monitor Your Network with the Real-time Traffic Analyzer
The main reason to monitor your network is to check that your all your servers are available. If there is a network problem you want an interface to show the scope of the problem at a glance.
Even when all servers and routers are available, sooner or later you will be curious to know who, or what, is hogging your precious network’s bandwidth. A GUI showing the top 10 users makes interesting reading.
Another reason to monitor network traffic is to learn more about your server’s response times and the use of resources. To take the pain out of capturing frames and analysing the raw data, Guy recommends that you download a copy of the SolarWindsfree Real-time NetFlow Analyzer.
Example 4: How to Stop a Service
In real life, you may want a script which ensures that services such as: Telnet, Messenger and Routing and Remote Access are Stopped. Just for testing, you may need a script which reverses start-Service, just to be sure that it really is working as designed. Either way, here is a script which stops the service defined by $srvName.
# PowerShell cmdlet to stop the Plug & Play service
$srvName = «PLA»
$servicePrior = Get-Service $srvName
«$srvName is now » + $servicePrior.status
stop-Service $srvName
$serviceAfter = Get-Service $srvName
set-Service $srvName -startuptype disabled
«$srvName is now » + $serviceAfter.status
Learning Points
Note 9: Observe how this script is the mirror image of the Start-Service script. It even disables the service once it has stopped. If you remember, when Example 1 wanted to start a service, it must first make sure the -startuptype is set to manual.
The ‘-Service’ Family (Each member has a different verb)
Clear-Host
Get-Command -Noun Service
Get-Service: Useful for listing the services
Set-Service: Crucial parameter -startuptype
Start-Service: The verb ‘start’ says it all
Stop-Service: Handy for scripts which prevent unwanted services running e.g. Telnet
Restart-Service: A nice touch by the creator’s of PowerShell; this cmdlet removes the need to explicitly stop then start the service.
Guy Recommends: SolarWinds Engineer’s Toolset v10
This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems. Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.
There are so many good gadgets; it’s like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools. Try the SolarWinds Engineer’s Toolset now!
Download your fully functional trial copy of the Engineer’s Toolset v10
Remoting with PowerShell Service
One aspect of remoting in PowerShell v 2.0 is simply to append -computerName xyz to the command that you ran on the local machine. For further research try:
Clear-Host
Get-Command | where { $_.parameters.keys -Contains «ComputerName»}
Surprise! Get-Service is amongst the cmdlets that support remoting, but stop, start and restart-Service are not on the list. More bad news, stop, start and restart-Service really don’t work on network machines. Thus you have to employ different techniques such as Get-WmiObject and InvokeMethod. Alternatively, you could enter-PSSession and then run restart-Service as if you were on the local machine. However, to get that working you have to first install and setup WinRM
»
Summary of PowerShell’s Start-Service Cmdlet
If your mission is to master the start-Service command, commence with Get-Service. Once you have mastered the rhythm of the Get-Service Verb-Noun pair, move on to the Start, Stop, and restart-Service family of PowerShell commands. For scripting purposes, make sure that you use the true Service Name, and avoid the Service’s Display Name. A final piece of advice, open the Service GUI so that you can double-check that what your script is doing is what you intended.
If you like this page then please share it with your friends
See more PowerShell examples of process and service
• PowerShell Home • Get-Process • Stop-Process • PowerShell Start-Process • Set-Service
• Get-Service • Start-Service • Stop-Service • Restart-Service • Free WMI Monitor
• PowerShell Start-Sleep • Get-WmiObject win32_service • Windows PowerShell
Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.