3

Say that I want to start MSSSQLSERVER service. this is done in PowerShell via the Start-Service cmdlet.
Sometimes services fail to start due to an error like in the example below. What I'm interested in is the root cause of the failure, while start-service seems to be returning the powershell exception, a generic wrapper that does not contain error-specific information.

PS C:\Users\Administrator> start-service MSSQLSERVER
start-service : Failed to start service 'SQL Server (MSSQLSERVER) (MSSQLSERVER)'.
At line:1 char:1
+ Start-Service MSSQLSERVER
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
   ServiceCommandException
    + FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand

To get the root cause of the problem, we have to resort to net start command, that brings us back to the old-days that should be forgotten with PowerShell.

C:\Users\Administrator>NET START MSSQLSERVER
The SQL Server (MSSQLSERVER) service is starting.
The SQL Server (MSSQLSERVER) service could not be started.

A service specific error occurred: 17051.

More help is available by typing NET HELPMSG 3547.

Is there a way to see the underlying error thrown by the service?

Ansgar Wiechers
  • 184,186
  • 23
  • 230
  • 299
AgostinoX
  • 7,165
  • 18
  • 75
  • 126

2 Answers2

6

As I.T Delinquent stated, the error can be found in the exception, however in this case it will be stored in the inner exception(s):

$ErrorActionPreference = "Stop"

try
{
    Start-Service -Name "MSSQLSERVER"
}
catch
{
    $msg = @()
    $err = $_.Exception
    do {
        $msg += $err.Message
        $err = $err.InnerException
    } while ($err)

    Write-Verbose "Failed to start service: $($msg -join ' - ')"
}
mhu
  • 17,439
  • 10
  • 60
  • 87
  • I found searching can be more reliable with `NativeErrorCode` (like [here](https://stackoverflow.com/questions/24228307/error-1053-the-service-did-not-respond-to-the-start-or-control-request-in-a-time)) so I use `"Error $($err.NativeErrorCode): $($err.Message)"` – davetapley Nov 23 '21 at 22:56
  • @davetapley Thanks for the addition, for service operations it should work, but please note that `NativeErrorCode` is not available with all exceptions (types) – mhu Nov 24 '21 at 19:11
2

I think it would be good for you to check out this link

But basically, you can use a Try/Catch statement and output the message from the error, something like this:

try{
    Start-Service MSSQLSERVER -ErrorAction Stop
}catch{
    $PSItem.Exception.Message
}
I.T Delinquent
  • 2,135
  • 2
  • 16
  • 28