How To Start and Stop Services Using PowerShell Remotely
Admit it, you’re an admin that likes to do everything possible from the desk or laptop and if possible from a command line because automation is our friend.
With the addition of PowerShell this is getting more of the norm for Windows and starting and stopping services remotely is probably one of the most used. To perform this task we will need to several cmdlets, some
- get-service
- stop-service
- start-service
- restart-service
So for this post we will be stopping and starting the Windows Update Service. First we need to find the name of the service, we can do this using the get-service cmdlet and findstr commands.
PS C:\> get-service -ComputerName cvgwin2008tst | findstr /c:"Windows Update" Running wuauserv Windows Update
From this command we see get-service -ComputerName <computername> and then use the pipe symbol and use findstr with the /c: switch for using specified text as a literal search string and the status, name and display name are shown.
So we know wuauserv is the name of the service. So next lets create a variable called $service and populate it with this information.
PS C:\> $service = get-service -ComputerName cvgwin2008tst -Name wuauserv PS C:\> $service Status Name DisplayName ------ ---- ----------- Running wuauserv Windows Update
So now we want to stop the service but there is a catch, the stop-service cmdlet doesn’t support the -ComputerName parameter but it does support the -InputObject parameter. So let’s stop the service and make the command gives a status of what it is doing using the -Verbose parameter.
PS C:\> Stop-Service -InputObject $service -Verbose VERBOSE: Performing operation "Stop-Service" on Target "Windows Update (wuauserv)"
Run $service and see that it has been stopped.
PS C:\> $service Status Name DisplayName ------ ---- ----------- Stopped wuauserv Windows Update
Now using the start-service cmdlet let’s fire it back up.
PS C:\> Start-Service -InputObject $service -Verbose VERBOSE: Performing operation "Start-Service" on Target "Windows Update (wuauserv)". PS C:\> $service Status Name DisplayName ------ ---- ----------- Running wuauserv Windows Update
Now that all pieces are in place you can save all the commands as a ps1 and just run a single command!
I’d like to extend this by stopping additional services, but only after confirming the initial service has been stopped. Is it possible to loop the status check without piping the check to a file and parsing the file?
I will take a look into it. I wrote this script awhile back and that way I wrote it fit the need at the time.