Время на прочтение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
What’s the best way to restart a Windows Service remotely from our central domain server?
— Sylvia W.
Hi Sylvia.
We know of at least five ways to restart a Windows Service on a remote machine. Let’s review each method, focusing on the pros and cons to help you select the approach that best fits your situation.
Note: If any of the methods fail with security related errors (such as “access denied”), you may need to update security settings on the remote machine.
Method #1: Use the Services application to connect to the remote PC
Did you know that the Services application works with remote computers? For some reason, Microsoft buried that feature in the interface, making it very easy to miss!
To view services on another computer:
-
Start the Services application
-
In the left panel, right-click Services (Local) and select Connect to another computer from the menu:
-
In the Select Computer window, specify the computer hosting your Windows Service:
-
Click OK to access the remote PC
-
The Services application should refresh to list the services on your other computer. From there, you can start or stop any service you like:
If that didn’t work, you may need to update your security settings.
Pros
-
Services is a standard utility that is available on every Windows computer.
-
Services is very easy to use.
-
Besides starting or stopping the service, you can also update the service’s properties. For example, you can disable the service, setup failure actions or change the log on account.
Cons
-
Working with Services is interactive. You (or your tech) must log in, start Services, connect to the remote PC and start the service. You can’t call Services from a batch file. As a result, this approach is not suitable for non-interactive situations.
Method #2: Run SC with the “server” command line parameter
If you’re comfortable working from the command prompt, the SC utility should be in your toolbox.
To stop a Windows Service on another machine, run:
SC \\<SERVER-NAME> STOP <SERVICE-NAME>
For example, to stop the Spooler service on our file server (named “ctc-file-server”), we run:
SC \\ctc-file-server STOP Spooler
Be sure to run SC from an elevated command prompt — run as an administrator. If not, the command could fail because of insufficient permissions.
Pros
-
SC is a standard utility that is available on every Windows computer.
-
With SC, you can easily start or stop a service.
-
You can call SC from a batch file, which makes it suitable for non-interactive scenarios.
-
SC can do much more than start or stop a service. You can use it to change a service’s properties as well. In fact, it supports many more settings than the Services application does. Run SC /? to see the full set of options available.
Cons
-
When starting or stopping a service, SC simply makes a request and exits. It will not wait for the service to transition to the desired state. Unfortunately, that behavior can cause complications in batch files. For example, if you call “SC STOP” immediately followed by “SC START”, the start command will fail if the service takes a few seconds to stop.
Method #3: Install and run Microsoft’s PsService
If you’re familiar with the amazing (and free) tools from Microsoft’s SysInternals group, you should definitely check out their PsService utility.
Like SC, PsService allows you to start, stop or restart your service from the command line. And importantly, PsService works with remote computers.
In fact, PsService offers a rich set of command line options. Run PsService /? to see them:
Look closely and you’ll see that PsService offers one important capability that neither SC nor Services does — the ability to specify the account to use on the remote computer. That feature comes in handy if your account doesn’t have enough rights or if you want to use a specific account to control the service.
For example, to start the Spooler service on our “ctc-file-server” computer, we run:
PsService \\ctc-file-server start Spooler
Pros
-
PsService is safe, free, reliable and endorsed by Microsoft.
-
With PsService, you can easily start or stop a service.
-
You can call PsService from a batch file, which makes it suitable for non-interactive scenarios.
-
With PsService, you can specify the username and password of an administrative account on the remote PC. As a result, your account doesn’t need to have administrative rights on the remote computer.
Cons
-
PsService does not come pre-installed on your computer. You will have to download and install/unzip the PSTools suite to use PsService. This may be an issue if you are operating in a “locked down” environment where adding new software is difficult.
-
When starting or stopping a service, PsService simply makes a request and exits. It will not wait for the service to transition to the desired state. Unfortunately, that behavior can cause complications in batch files. For example, if you call “PsService stop” immediately followed by “PsService start”, the start command will fail if the service takes a few seconds to stop.
Method #4: Use Microsoft’s PsExec to run NET
PsExec is another powerful tool in the SysInternals arsenal. It allows you to run arbitrary commands on a remote computer.
Running the NET command with PsExec produces a command that will start or stop your service and wait for it to complete. That may be an important improvement over SC and PsService, which simply put in a request and exit.
For example, this command stops the Spooler service on our “ctc-file-server” computer:
PsExec \\ctc-file-server NET STOP SPOOLER
Pros
-
PsExec is safe, free, reliable and endorsed by Microsoft.
-
With PsExec and NET, you can easily start or stop a service.
-
You can call PsExec from a batch file, which makes it suitable for non-interactive scenarios.
-
With PsExec, you can specify the username and password of an administrative account on the remote PC. As a result, your account doesn’t need to have administrative rights on the remote computer.
-
PsExec with NET will wait for your service to start or stop before returning.
Cons
-
PsExec does not come pre-installed on your computer. You will have to download and install/unzip the PSTools suite to use PsExec. This may be an issue if you are operating in a “locked down” environment where adding new software is difficult.
-
NET waits up to 30 seconds for the service to start or stop. That may not be enough time for a service that takes a long time to transition.
Method #5: Use PsExec to run ServicePilot
If your service takes a while to start or stop, you may want to use our free ServicePilot utility instead of NET. With ServicePilot, you are not limited to a 30-second timeout.
ServicePilot is better than NET in other ways too. For example, ServicePilot can restart a service in one operation (instead of issuing a stop followed by a start) or forcibly terminate a misbehaving service.
This command uses ServicePilot to start the Spooler service on our “ctc-file-server” computer:
PsExec \\ctc-file-server C:\Apps\ServicePilot.exe -start Spooler
Note that the command above assumes that the ServicePilot executable is available on the remote machine. If that is not the case and you only have ServicePilot on the local machine, you must instruct PsExec to copy the executable to the remote PC by specifying the -c parameter. Here is what that command looks like:
PsExec \\ctc-file-server -c «C:\Apps\ServicePilot.exe» ServicePilot.exe -start Spooler
Even though it’s less efficient, having PsExec copy the executable each time might be the better option for occasional (and unplanned) use cases.
Pros
-
ServicePilot is safe and free.
-
With PsExec and ServicePilot, you can easily start or stop a service.
-
You can call PsExec from a batch file, which makes it suitable for non-interactive scenarios.
-
With PsExec, you can specify the username and password of an administrative account on the remote PC. As a result, your account doesn’t need to have administrative rights on the remote computer.
-
PsExec with ServicePilot will wait for your service to start or stop before returning.
Cons
-
Neither PsExec nor ServicePilot come pre-installed on your computer. You will have to download them. This may be an issue if you are operating in a “locked down” environment where adding new software is difficult.
That’s it. Hopefully one of these five methods works for you.
Appendix: Update security settings to access your remote service
Windows does a great job of locking down services. As such, you may have to relax the rules if you want to start or stop a service remotely.
Ensure that your account has sufficient rights on the remote machine
Are you sure that your Windows account can update the service?
Can you log in to the remote machine and start or stop the service?
If not, you’re probably missing permissions. You may have to:
-
Make your account an administrator on the remote computer. By default, only administrators can manipulate Windows Services.
-
Give your account permission to access the service. Log in to the remote computer and use our free Service Security Editor utility to adjust the service’s permissions:
Disable UAC remote restrictions
If you are not in a domain, your requests may be blocked by User Account Control (UAC) remote restrictions. Essentially, to enforce the principle of least privilege, Windows may not respect your administrative rights on the remote computer.
But there is a simple fix. You can disable UAC remote restrictions by updating the registry as follows:
-
Open the Windows Registry Editor (regedit)
-
Navigate to this key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
-
Look on the right side. If there is no value named LocalAccountTokenFilterPolicy, create it by selecting Edit > New > DWORD (32-Bit) Value and naming it.
-
On the right side, right-click LocalAccountTokenFilterPolicy and select Modify. Enter a value of 1:
-
Click OK to save your changes.
-
Close Registry Editor
You may also like…
To stop a Windows service on a remote computer using PowerShell, you can use the following command:
Stop-Service -Name 'ServiceName' -ComputerName 'RemoteComputerName' -Force
Make sure to replace `’ServiceName’` with the actual name of the service you wish to stop and `’RemoteComputerName’` with the target computer’s name or IP address.
Understanding Services in Windows
What are Services?
Windows Services are specialized applications that run in the background, performing tasks without direct user interaction. These services can be essential for system operations, including web hosting, security, and background processing. Understanding how to manage these services effectively is critical for any IT professional.
The Role of PowerShell in Service Management
PowerShell provides a powerful, scriptable interface for managing Windows Services. Unlike traditional management methods, which may involve navigating complex graphical interfaces, PowerShell enables administrators to execute commands swiftly, automating repetitive tasks. By mastering PowerShell, IT professionals can increase efficiency and minimize downtime.
PowerShell: Start Service on Remote Computer Easily
Prerequisites for Stopping Services Remotely
Ensure Remote Management is Enabled
To stop a service on a remote computer using PowerShell, it’s vital to ensure that remote management is enabled on the target system. PowerShell remoting is based on Windows Remote Management (WinRM). To verify and enable PowerShell remoting, run the following command in an elevated PowerShell window:
Enable-PSRemoting -Force
This command configures WinRM, setting up the necessary listeners and firewall exceptions for remote managing tasks.
User Permissions and Rights
Another critical factor is user permissions. To stop services on a remote computer, you must have administrative privileges on that machine. If you are unsure about your permissions, you can check your user rights or contact the system administrator to verify that you have the necessary access.
PowerShell Get Service on Remote Computer Simplified
PowerShell Cmdlets for Service Management
Key Cmdlets Overview
PowerShell offers several cmdlets for managing services effectively, with `Get-Service` and `Stop-Service` being the most commonly used.
- Get-Service: This cmdlet retrieves the status of services on a computer.
- Stop-Service: This cmdlet is used to stop a running service, based on its name or display name.
Understanding these cmdlets serves as the foundation for managing services via PowerShell.
PowerShell Get-PSDrive on a Remote Computer Explained
Stopping a Service on a Remote Computer
Basic Syntax for Stopping a Service Remotely
The basic syntax to stop a service on a remote computer is straightforward:
Stop-Service -Name "ServiceName" -ComputerName "RemoteComputerName"
In this command:
- `ServiceName` refers to the name of the service you wish to stop (e.g., `wuauserv` for Windows Update).
- `RemoteComputerName` is the name or IP address of the target machine.
Example: Stopping an Example Service
To illustrate stopping a particular service, here’s an example command to stop the Windows Update service on a remote machine named Server01:
Stop-Service -Name "wuauserv" -ComputerName "Server01"
This command will immediately cease the operation of the Windows Update service on Server01. It’s essential to ensure that ceasing the service does not disrupt other processes or applications.
PowerShell Run Script on Remote Computer: A Quick Guide
Handling Common Errors
Troubleshooting and Error Messages
When running commands to stop services remotely, you might encounter various error messages. Common issues include:
- Access Denied: This usually indicates that your user account lacks the necessary permissions on the remote machine.
- Service Not Found: This error appears if the service name is incorrect or if the service is not running on the remote computer.
To troubleshoot these errors, verify your permissions and ensure you are using the correct service name. For example:
Get-Service -ComputerName "Server01"
This command lists all services on Server01. You can check if the intended service is running and its correct name.
PowerShell Restart Service Remote: A Quick Guide
Alternative Methods
Using PowerShell Remoting
An alternative method for stopping a service remotely is to utilize the `Invoke-Command` cmdlet. This method allows you to run commands on multiple computers simultaneously. Here’s how you can stop a service using `Invoke-Command`:
Invoke-Command -ComputerName "RemoteComputerName" -ScriptBlock { Stop-Service -Name "ServiceName" }
This command directs PowerShell to execute the stop-service command within the script block on the specified remote computer. The advantage of this approach is that it can run multiple commands or scripts as part of one operation.
Using Task Scheduler for Service Management
Sometimes, you may want to schedule service management tasks for convenience or routine maintenance. Using Windows Task Scheduler, you can configure jobs to stop services at specified times or events. This approach can help automate processes without requiring manual intervention and ensures smoother operation overall.
PowerShell to Connect to Remote Computer: A Quick Guide
Best Practices for Remote Service Management
Security Considerations
When managing services remotely, it’s crucial to prioritize security. Always utilize secure connections, such as those established through HTTPS. Ensure that you are using strong passwords and consider implementing multi-factor authentication for additional security. Familiarize yourself with PowerShell’s security features and principles to minimize potential risks.
Testing Commands Before Execution
Before executing stop commands on a critical service, it’s a good idea to simulate the command’s impact using the `-WhatIf` parameter. This allows you to see what would happen without actually making changes to the service state. For example:
Stop-Service -Name "ServiceName" -ComputerName "RemoteComputerName" -WhatIf
This precaution helps ensure that you fully understand the command’s effects and can avoid unintended service interruptions.
PowerShell Shutdown Remote Computer: A Quick Guide
Conclusion
PowerShell provides a powerful and efficient means to manage services on remote computers, particularly with the `Stop-Service` cmdlet. By following the outlined prerequisites, understanding proper syntax, troubleshooting common issues, and adhering to best practices, IT professionals can effectively navigate the complexities of remote service management while ensuring the security and stability of their environments.
PowerShell Script Remote Execution Made Simple
Additional Resources
To deepen your understanding and capabilities with PowerShell and service management, consult the following resources:
- Microsoft’s official PowerShell documentation for cmdlet syntax and examples.
- Online forums and communities focusing on PowerShell scripting best practices.
- Tutorials and courses on PowerShell remoting and service management.
This guide demonstrates how to start & stop Windows service remotely, which will allow you to configure Windows services across multiple devices with PowerShell, the Windows Services Manager, or by remote desktop. Furthermore, we explore why it’s important to deploy tools for managing Windows services for secure remote management in an enterprise environment.
About Remote Windows Services Management
Windows services are programs that run in the background and don’t require your input. They do not have an application window or icon on the taskbar, so they’re mostly hidden from view. Their purpose is to provide system functionality from the point your computer starts up, including things like sound and networking that are built into the Windows operating system, and software you install yourself like antivirus and VPNs.
Windows services can be managed remotely, allowing you to start and stop service over a network connection. This is useful in enterprise and corporate scenarios for IT administration (for example, to start a VPN service on a remote machine after it has been installed), but also useful for home users with multiple Windows devices they want to keep control over.
There are several built-in ways to start/stop Windows services remotely, including using PowerShell, the Windows Management Instrumentation (WMI) interface, and remote desktop.
How to find a Windows service name
To start or stop a Windows service you need to know its name. This can be found in Windows Services Management by following these steps:
- Right-click on the Start menu.
- Click Run.
- Type services.msc and hit enter to launch Windows Services Manager.
- All configured services will be listed. This also works when using the remote Windows Management Instrumentation (WMI) steps shown below.
If you are working in PowerShell, you can run the following command to list all services using the Get-Service cmdlet:
Get-Service | Sort-Object Name
Note that the service name may be different from its display name.
How to start and stop Windows service remotely using PowerShell
The most efficient way to start or stop a Windows service remotely is using PowerShell. Before you can do this, you need to enable remote management on the remote computer by running the following command:
Enable-PSRemoting -Force
This executes the Enable-PSRemoting cmdlet with the -Force option, so it will not prompt for confirmation.
Note that it is vital that you read and understand PowerShell commands before running them, so that you do not accidentally perform an action that may damage your system.
On non-server versions of Windows, the Enable-PSRemoting command will automatically create a Windows Firewall rule allowing remote management. To enable this rule, run the following PowerShell command on the remote computer:
Enable-NetFirewallRule -Name “WINRM-HTTP-In-TCP-Public”
Finally, prompt for credentials and run the Start-Service cmdlet remotely to start a service:
$credentials = Get-Credential
Invoke-Command -ComputerName “COMPUTER_NAME” -ScriptBlock {
Start-Service -Name “SERVICE_NAME”
} -Credential $credentials
In the above command, you will need to replace:
- COMPUTER_NAME with the network name of the remote computer you want to start the service on.
- SERVICE_NAME with the name of the service you want to start.
If you want to stop a service, replace the Start-Service cmdlet with Stop-Service
$credentials = Get-Credential
Invoke-Command -ComputerName “COMPUTER_NAME” -ScriptBlock {
Stop-Service -Name “SERVICE_NAME”
} -Credential $credentials
In both of the above start/stop examples, the Get-Credential cmdlet is used to prompt the user for the username and password for the remote machine.
Then, Invoke-Command is called to send a block of code (using the -Scriptblock parameter, and the code surrounded by curly braces) containing the Stop- or Start-Service cmdlet, along with the previously stored $credentials.
How to start or stop a service on multiple Windows PCs
The above PowerShell commands can be adapted to run on multiple remote Windows machines simultaneously, allowing you to start and stop services on all of them with a single command:
$computers = “COMPUTER_NAME_1”, “COMPUTER_NAME_2”, “COMPUTER_NAME_3”
$credentials = Get-Credential
Invoke-Command -ComputerName $computers -ScriptBlock {
Stop-Service -Name “SERVICE_NAME”
} -Credential $credentials
Above, a list of remote computers’ network names have been listed in the $computers variable. This variable is then passed to the -ComputerName parameter in Invoke-Command (rather than passing a single computer’s name in the previous examples). The command will be sent to all of those computers and executed. This does, however, depend on the provided user credentials matching on all the listed machines.
How to start and stop Windows service remotely using Windows Management Instrumentation (WMI)
The Windows Service Management console used to find the names of services, mentioned earlier in this article, can also be used to remotely manage Windows services.
To do this, click on Action in the menu bar, and then Connect to another computer…
You will then be prompted to enter the network name of the remote computer to connect. Windows Management Instrumentation (WMI) allows you to use Windows Services Management to control the services on the remote machine, as if you had run services.msc on that machine itself.
Once connected, you can view the list of services and can right-click on them to stop or start them.
Using Remote Desktop Protocol (RDP) for remote IT administration
Windows contains built-in remote desktop functionality. When using this, you have a full view of the remote computer’s desktop, with full control over the keyboard and mouse, just as if you were sitting in front of it.
This allows you to use all the local service management tools, including the Windows Services Manager console and PowerShell.
To connect to a Windows computer using Remote Desktop, follow our guide here.
Use cases for remotely managing Windows services
There are several common scenarios for managing Windows services remotely:
- Managing Windows services on small networks: Small office and home networks can be administered with simple tools. Using remote desktop to perform system maintenance tasks is not unusual in this environment, though it is inefficient if you manage multiple small networks.
- Managing Windows services on medium-sized networks: On medium-sized networks, using WMI tools and the tools provided by Windows domain controllers can streamline IT operations and make managing remote machines, including running services, more efficient.
- Managing Windows services remotely on enterprise-scale networks: In education and large-scale business networks, especially those where users may bring their own devices (BYOD) or work remotely via VPN, maintaining the security and usability of Windows devices can be a challenge. Remote Monitoring and Maintenance (RMM) can assist by providing a unified and automated management platform for all of your devices in an end-to-end solution.
Which method you use will probably depend on whether this is a once off task, or whether you will be regularly starting and stopping Windows services on multiple computers.
Scripting and automation play a key role in efficiently managing fleets of Windows devices. For example, if you are constantly restarting services on remote machines, you can use the PowerShell command shown in the above example in a script that runs periodically.
Remote windows management
In mission-critical environments, the best solution for ensuring that remote services are running correctly is to use a remote monitoring and management solution. NinjaOne RMM gives your IT team full visibility over your entire IT infrastructure, including what services are running on each machine, and can alert you of any programs that may be making computers run slowly.
Integration with antivirus and firewall solutions means that if a user installs a service that acts suspiciously, you can be alerted and take proactive measures to isolate and deal with the problem before it affects your business operations.
Computers in the home are obviously very common these days and it’s not unusual to find more than one Windows PC or laptop in a household. Perhaps the parents have the desktop PC and the kids use a laptop or you have desktop machines networked together in your office for work. With the increase in computers at your disposal comes an increase in looking after them when they developed a problem, need tweaking or don’t work as efficiently as they should.
One of the ways to work on another computer without physically being in front of it is of course via networking. Besides the obvious of being able to read and execute files on a remote computer or transferring files between computers, you can also perform more advanced maintenance tasks such as starting or stopping remote processes and even controlling Windows Services to be started, stopped or completely disabled.
Here we’ll show you some ways to view the status of Windows Services on a remote computer in addition to having the ability to start and stop them without leaving your own computer.
1. Yet Another (Remote) Process Monitor
This program hasn’t been updated since 2009 but YAPM is one of few tools that can actually let you manage remote services from the comfort of a GUI. We have talked about the program before because of the remote process handling abilities, but it’s equally at home controlling services.
YAPM allows you to view the services and their details on the remote machine. It offers control of starting, stopping, or changing the startup type. There are two ways to remotely connect to another computer; either via the easier WMI interface, or launching a YAPM server process on the remote machine (this option doesn’t seem to work too well these days).
For ease of use, we’ll show the WMI option. Run YAPM and click the round Options button near the top left of the window, select “Change connection type” from the menu. This will bring up the connections window, click “Remote via WMI” followed by Disconnect, and then enter the remote computer name or IP address along with the remote admin’s username and password. Finally, click Connect and then Hide window.
In the main window, select the Services tab and after a few moments you should see all the services on the remote computer (refresh if not). Now you can view and control the remote services as if they’re on your own machine with buttons or context menu options to start, stop, set to autostart, on-demand startup (manual), or disable from starting. YAPM requires .NET 3.5 for Windows 10 users, a portable version is also available.
Download Yet Another (Remote) Process Monitor
2. Application Access Server (A-A-S)
A-A-S is an old tool that actually boasts several powerful features. Sadly, it can be tricky to use and the official documentation isn’t very helpful. With the ability to launch Windows applications and enable/disable services remotely over the internet as well as a local network, A-A-S has good potential uses. A possible drawback is it needs to be configured and run entirely on the remote computer.
To get up and running quickly you don’t need to configure that much. First, run the program and click on Configure > User, highlight user admin in the list, and click change. Replace the password and optionally the username, click OK. You can also change the port from the default of 6262 to something like 80 which will get around firewall port restrictions. Press Start to launch the web server.
Now go to a computer on the network you wish to connect from and open a web browser. Enter the IP address of the computer with A-A-S on it in the address bar and append the port number (no need if you use port 80), so it would look something like:
http://192.168.0.45:6262
You will then be prompted for the username and password of the user edited above. In the web interface, click the Services option on the left. The window will display the services on the remote computer along with their current status. Do note that A-A-S can’t tell the difference between a disabled service or just a stopped service. For this reason, when you press to Start a remote service it might not actually start because it’s startup state is set to Disabled.
Services with Manual or Automatic startup types will accept Start/Stop requests but Pause will likely fail. A-A-S offers extra security measures such as Silent or Stealth port options. Silent requires a keyword appended to the IP address and port while Stealthed uses a separate AAS_Login.exe tool. Services can also be started and stopped using command line tools like Net or SC, this can be done in the Application configuration window.
Download Application Access Server
3. Controlling Remote Services via Command Prompt
The Windows built in SC command is basically a console based version of the Services MMC snap in. It does have a problem because there is no ability to log on as another user on the remote computer. Thankfully, combining SC with the NET USE command, we can connect to the remote computer and then perform service tasks. Bring up an admin Command Prompt (Start > type cmd > Ctrl+Shift+Enter) and then type the following:
Net Use \\computername password /User:username
The NET USE command first creates a connection to the remote computer with the credentials of one of its administrators. Then you can use the SC command to query the status of a service and start/stop or change its startup type. A few examples are:
Query whether the service is running or stopped:
SC \\computername Query servicename
Query the service startup type, path, display name, dependencies, and etc:
SC \\computername QC servicename
Start or stop a service:
SC \\computername Start|Stop servicename
Change the service startup type:
SC \\computername Config servicename start= Auto|Demand|Disabled
Note: The single space after “start=” is important and must not be omitted!
The above screenshot queries the Windows Update Service on the remote machine, starts it, and then queries it again to check the service has started. More information on how to use the SC command can be found at Microsoft Technet or third party sites like SS64.Com.
If you wish to terminate the connection with the remote computer, either reboot the computer or run “Net Use \\computername /Delete”.
4. Sysinternals PsService (part of PsTools)
The Microsoft owned developer Sysinternals has a set of command line utilities for local and remote administration called PsTools. One of the included tools is PsService and it’s specifically made to handle remote services. The advantage this tool has over SC is the option to supply the user name and password of a user on the remote machine, so the NET command isn’t needed. The syntax is:
Psservice \\computername -u username -p password command options
As PsService supplies user credentials as arguments, you don’t need to include the Net Use command. The basic commands are broadly the same as the Windows SC utility such as query, config, start, stop, and etc. Here are a few examples for handling the Windows Search Service:
Query the service:
Psservice \\computername -u admin -p pass Query wsearch
Query the startup configuration of the service:
Psservice \\computername -u admin -p pass Config wsearch
Start or stop the service:
Psservice \\computername -u admin -p pass Start|Stop wsearch
Set the startup type of the service:
Psservice \\computername -u admin -p pass Setconfig wsearch Auto|Disabled|Demand
The above image stops the Windows Search Service and then disables it. To completely disable a service, make sure to stop it before setting its startup type. The full list of syntax and arguments can be found in the included help document or on the SysInternals website.
Download Sysinternals PsTools (includes PsService)
5. Services/Computer Management Console
This method might be the easiest to use because it doesn’t rely on third party tools or the command line and is built into Windows. However, it can also be a bit of a pain on some systems and there’s a chance you will get errors or connection problems.
a) Press the Windows key and type “services” to open the Control Panel Services applet. Alternatively, type Services.msc into the Win+R Run dialog. Go to the Action menu > “Connect to another computer”.
b) Click Browse and enter the name of the remote computer in the object name box. Press OK and you will be prompted for the username and password of an account on the remote computer.
If you can’t remember the remote computer’s name, click Browse > Advanced > Find now. This will show a list of computers in the local workgroup where you can find the PC you want to connect with. Click OK to get back to the main window.
c) The Services window should now have the remote computer’s name in the console tree instead of Local. From there, all you have to do is expand “Services and Applications” and go to Services.
The remote Services Control Panel applet works with services in the exact same way as if you was controlling services on the local machine.
Finding Windows Service Names
Windows has more than one name for each service; the Service name and its Display Name. For example, “Windows Update” is the display name for the Windows Update Service, Wuauserv is the service name.
The easiest way to use these tools is with the shorter service name, you can find names for services on your own computer if you’re not sure, open Task Manager and go to the Services tab, the Name column gives the name you need to use.
Alternatively, you can use the Control Panel Services applet (Services.msc) and double click the service to find the name near the top (pictured above). A useful resource for Service information including names for all versions of Windows is BlackViper.com.