Search code examples
powershellwindows-services

Start-Service cmdlet: get underlying error in case of failure


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?


Solution

  • 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 ' - ')"
    }