If you’re like me you don’t always need SQL Server running in a local development environment. Because of this I wanted a quick and easy way to start and stop SQL Server which immediately made me think of Windows PowerShell. This script is for PowerShell 2.0 and is pretty simple, you could get much more fancy but it suffices for my setup on my home development box.

Here’s the script:
[code lang="PowerShell"]
$service = get-service "MSSQLSERVER" -ErrorAction SilentlyContinue

if( $service.status -eq "Running" )
{
"Stopping Dependent Services..."

$depServices = get-service $service.name -dependentservices | Where-Object {$_.Status -eq "Running"}

if( $depServices -ne $null )
{
foreach($depService in $depServices)
{
stop-service $depService.name
}
}

"Stopping Service..."

stop-service $service.name -force

"Service Stopped"
}
elseif ( $service.status -eq "Stopped" )
{
"Starting Service..."
start-service $service.name
"Service Started"
}
else
{
"The specified service does not exist"
}
[/code]
I had wanted to use Try/Catch but the service commands (e.g. get-service) issue non-stopping errors which PowerShell 2.0 doesn’t catch.

Really this works on just about any service, but my use was for SQL Server, just change the name of the service to anything you like, or even better yet pass it in as a parameter. You could also have it start dependent services if you like.

Tags: ,