With a #notsogreat personal laptop, and having a lot of things installed, my laptop runs a bit slower. When I install sql server, i usually configure the services to start manually, so I can just start them when I need them. Being a .NET developer doesn’t require me to have Sql Server up and running all the time. But being lazy, I usually hate when I have to go to services and start / stop the service, so i wanted to have some kind of switch to turn it on and off whenever i needed. And I got this done using a powershell script, my first ever powershell script.
I started creating a variable that embedded all parameters i needed to get the sql service, and tried to find the service using Get-WmiObject:
$WmiObject = @{ Class = “Win32_Service” Filter = “name = 'MSSQLSERVER'” } $Svc = Get-WmiObject @WmiObject
Then, if service is found, check its state, and if it’s stopped, start the service, if it’s running, stop the service. If it’s in any other state, don’t do anything to it:
if($Svc -ne $null) { Write-Host "Found " $Svc.DisplayName "service. Service is currently" $Svc.State if ($Svc.State -eq 'stopped') { Write-Host "Starting the service..." Start-Service -DisplayName $Svc.DisplayName Write-Host $Svc.DisplayName "started!" } else { if ($Svc.State -eq 'running') { Write-Host "Stoping the service..." Stop-Service -DisplayName $Svc.DisplayName Write-Host $Svc.DisplayName "stopped!" } else { Write-Host "Service state is" $Svc.State ". Invalid state, exiting." } } } else { Write-Host "Service not found" }
I can and will also add the other services like sql server agent to it, and put the start/stop section within a foreach.
This gave a good quick answer to my laziness. I can now save this script in a ps1 file, and right click, Run with PowerShell, I or can make a .bat file to call this script in which the following line needs to be added to run the script:
powershell.exe -noexit "& '<your path to the file><your powershell filename>.ps1'"
Replace the placeholders as on your machine.
Download here the script file MSSQLSERVER – start.stop.ps1 .
0 Comments.