# startSqlService.ps1

# special provision to deal with SQL Server not starting up due to various reasons
$sqlServerService='mssqlserver'
$sqlWaitSeconds=120
$desiredState='Running'
$sqlWaitTimespan=[timespan]::fromseconds($sqlWaitSeconds)
if($sqlServerService -in $originalStoppedServices.Name){            	
    try{
    $sqlService=get-service $sqlServerService -EA Ignore
    if($sqlService.Status -ne $desiredState -and $null -ne $sqlService){
        $stopped=try{$sqlService.waitforstatus('Stopped',$sqlWaitTimespan);$true}catch{$false}
        if($stopped){
            $attempt=net start $sqlServerService /T902 2>&1
            $running=(get-service $sqlServerService).Status -eq 'Running'
            $running=if(!$running){try{$sqlService.waitforstatus('Running',$sqlWaitTimespan);$true}catch{$false}}else{$running}
            if($attempt -match 'started' -and $running){
                write-host "$sqlServerService has been started with trace flag /T902" -foregroundcolor Green
            }else{
                write-host "$sqlServerService has NOT been started with trace flag /T902" -foregroundcolor Red
            }
        }else{
            write-warning "$sqlServerService has current state is $((get-service $sqlServerService).Status)"
        }                 
    }                
    }catch{
    write-warning $_                               
    }            
}