Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Starting/stopping SQL Server services


This recipe describes how to start and/or stop SQL Server services.

Getting ready

Check which SQL Services are installed in your machine. Go to Start | Run and type services.msc. You should see a screen similar to this:

How to do it...

Let's look at the steps to toggle your SQL Server services states:

  1. Open PowerShell ISE as administrator.

  2. Add the following code:

    $verbosepreference = "Continue"
    $services = @("SQLBrowser", "ReportServer")
    $hostName = "localhost"
    
    $services |
    ForEach-Object {
       $service = Get-Service -Name $_
       if($service.Status -eq "Stopped")
       {
          Write-Verbose "Starting $($service.Name) ...."
          Start-Service -Name $service.Name
       }
       else
       {
          Write-Verbose "Stopping $($service.Name) ...."
          Stop-Service -Name $service.Name
       }
    }
    $verbosepreference = "SilentlyContinue"

    Note

    Be careful; the status may return prematurely as "started" when in fact the service is still in the "starting" state.

  3. Execute and confirm that the...