Service Management with PowerShell

PowerShell is great for automating administrative tasks. Common tasks may include managing services (stop, start, restart, etc). Here is some sample code to demonstrate some of the PowerShell service management capabilities. The first example is to stop a service, perform a task while the service is stopped, then start the service back up.

$svc = Get-Service "ServiceName"
# Send Stop Request to Service
$svc.Stop()
# Wait Until Service is fully Stopped
$svc.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped)

# Do something while service is stopped

# Finish by Starting the Service
$svc.Start()

Here’s an example for a simple service restart.

Restart-Service "ServiceName"

From Windows Task Scheduler, you can schedule a simple service restart with a command like this.

Powershell "& { Restart-Service 'ServiceName' }"

The WaitForStatus example was inspired by the powershell.com article “Waiting for Service State.” Note the use of optional timeout parameter in the linked article.

Advertisements

About notesbytom

Keeping technology notes on WordPress.com to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in System Administration and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s