AlwaysON Issues

Quarantined nodes in Windows Failover Clusters:

I’ve observed this issue on Windows Server 2016, where one of the nodes were quarantined after many node failover attempts in an hour. For the following few hours, the WSFC prevents the node from rejoining the cluster. This could be due to a network issue that I’ve noticed in the current environment. Quarantined receives a ping response from one node. Intermittently, the ping response from one node to the quarantined issue node receives a Timeout response.

For more details go through below link it helped me a lot :

https://www.mssqltips.com/sqlservertip/6714/windows-failover-cluster-node-quarantined/

2. You will encounter an error, The primary replica is not Active .The command cannot be executed.

This is due to an issue with the endpoint port not listening on the correct port or the tcp endpoint being stopped for some reason.

Go through below link for more :

https://techcommunity.microsoft.com/t5/sql-server-support/create-availability-group-fails-with-error-35250-failed-to-join/ba-p/317987

3. Unexpectedly, an availability group was missed, dropped, or removed.

This was caused by the fact that SQL was not being transmitted to WSFC. The SQL will then delete the Availability group.

Please go through below link for more details:

https://techcommunity.microsoft.com/t5/sql-server-support/issue-replica-unexpectedly-dropped-in-availability-group/ba-p/318175

4. Availability group is in Resolving State :

Issue : For a few minutes, there was a cluster failure that affected the availability group, and the replicas went into a resolving state. The replicas returned to their regular primary and secondary states once the cluster was brought back online, however several databases were still not synchronising. Furthermore, the databases on the primary were unavailable.

Resolution : The only remedy we found was to restart the primary replica’s SQL instance. Even a simple restart of the SQL service through the config manager, however, was stuck on “stopping service.” We had to use the TSQL command “SHUTDOWN WITH NOWAIT” to make SQL to stop. The databases were available again after SQL was brought back up, and AG was in sync and healthy.

For further details go through below link :

Issue : The secondary replica does not correctly transition to the primary role if an automated failover event fails. As a result, the availability replica will indicate that this replica is in the process of resolving. Furthermore, the availability databases state that they are not synchronising, and apps are unable to access them.

Reasons to occur :

Case 1 : The value of “Maximum Failures in the Specified Period” has been reached.
The clustered resource will fail three times in a six-hour period if the default behaviour is followed. RESOLVING STATE is applied to the AG replica.

Case 2 : Local SQL Server NT AUTHORITY\SYSTEM login account has insufficient NT Authority SYSTEM account rights. The following permissions are provided by default to this local login account:

Alter Any Availability Group
Connect SQL
View server state

Case 3 : If one of the availability databases in the availability group is in the synchronizing or not synchronized state, automatic failover will not be able to successfully transition the secondary replica into the primary role.

To get more details check below link :

https://docs.microsoft.com/en-us/troubleshoot/sql/availability-groups/troubleshooting-automatic-failover-problems

5 . Diagnose Unexpected Failover or Availability Group in RESOLVING State

Lease Timeout : A lease timeout can be triggered if SQL Server does not react within the normal 20-second lease timeout period.

Lease Timeout CAUSE – 100% CPU Utilization: A lease timeout might occur if CPU utilization is extremely high for an extended length of time. Using Performance Monitor, keep an eye on your CPU usage.

Sync Issues :

how to troubleshoot Always On synchronization issue?
Multiple reasons for the database status changing to not in sync

  1. Network Issue
  2. Huge transactions
  3. Space Issues

Restore All Databases from Backup Path Using DBATOOLS

I had a circumstance where I needed to restore 100’s of databases from a source server to a destination server, and we had to do it manually one by one, or manually build restore scripts for all databases using T-SQL scripts, or automate the process using PowerShell. I’m planned to use PowerShell to move the databases, however while searching, I came across DBATOOLS, which appears to be a quick and straightforward operation. To accomplish this, we must first install the DBATOOLS Module, and then update it if it is already installed. We used to get Database Refresh requests from Production to DEV/TEST on a regular basis as Database Administrators.

I installed and upgraded DBATOOLS on my machine, then I developed 3 databases to test migration from one instance to another. I already have database backup files in a folder to conduct our work, and now I’m testing to start restoring all 3 databases using DBATOOLS in PowerShell. To restore a database using DBATOOLS, we need to know the Restore command in PowerShell. We can check this in PowerShell using the Get-help *restore* command, which will display all of the available restore commands as well as a synopsis to help us figure out which restore command we can use to complete our task.

I use the command Restore-DbaDatabase from the DBATOOLS commands listed above. I’m only using this command since my backup files are already in a directory with Databases Full Backups, and I need to restore databases from these backup files.

In the above screenshot you can see 3 backup full files for test purpose, I use above backup path in our restore command to restore databases in my destination instance. Also I need to specify some parameters in Restore command like Destination Instance Name, backup Path, destination DATA Directory and Destination LOG Directory

Below is the Complete Restore command used in PowerShell :

You can see in the above Snippet that I ran the Restore command with the parameters passed in, and at the top you can see the restore database operation is in progress, as well as the percent completion of the restore is showing in  a Progress bar. Once the Database Restore is complete, it generates an Output that contains the information details. In the Output, we can see the Script Field, which contains the T-sql script used by DBATOOLS to restore databases. We may copy that T-sql script and use it for future restorations.

All 3 databases were successfully restored to my destination instance and the databases are ONLINE.

We may generate Restore Script for all Databases in a Backup path without restoring them to the Destination Instance by using the same command. We just need to add one parameter to the Restore command: -OutputScriptonly. Below is the Full Restore command :

Restore-DbaDatabase -SqlInstance DESKTOP-02JIB76\INS17 -Path 'E:\Backup\INS17' -DestinationDataDirectory 'D:\INS17\DATA' -DestinationLogDirectory 'D:\INS17\LOG' -WithReplace -OutputScriptOnly

When you execute above command it generates the Restore commands for all 3 databases and provides like below :


You can copy the Restore script to your SSMS and will looks like below :

Testing looks Good , I will use this in my current organization Environment .

Automate Migrating Databases From Source to Destination USing PowerShell

Using a combination of PowerShell and T-SQL scripting, create a simple solution for automating database migration across SQL Server versions. In my instance, I need to locate multiple databases that can be migrated using a standard procedure or at the very least a set of standard activities before proceeding to a set of customized actions. In these situations, you may want to create generic migration scripts and create a system to automate their execution. If you’re going to iterate through numerous test sessions and want to migrate a new copy before each one, a general technique like this can be extremely useful.

The activities that can be taken to make the migration process easier are as follows:

1) The backup database from the Source Instance will be transferred.
2) Restore the database that will be moved to the new instance.
3) Refresh the allocation usage.
4) Data purity can be used to check database consistency.
5) Set the level of page verification.
6) Set the database compatibility level to match the version of the destination instance (e.g. 120).
7) Statistics should be updated.
8) Remove any orphaned schemas (schemas automatically created for each database user to maintain compatibility but with no objects belonging to them).
9) Fix Orphaned Users if any exists.
10) Run Rebuild or re-organize all databases based on Migration Change window and the databases size.

Today, I’m automating the databases backup and restore of the first two Point. I still need to work on automating the other points, which are currently in process. I’m hoping that this backup and restore PowerShell script may be useful to some of the DBAs, and that I can share it now.

When you issue backup and restore commands in T-SQL, you’ll use handlers that are immediately called back by SMO, and you’ll provide a simple progress notification like the one provided by SSMS or sqlcmd. Please keep in mind that the completion handler just displays the error message.
Get-SQLInstance, DatabaseFullBackup, and RestoreDatabaseFromFullBackup are only a few of the functions in the Powershell script.

Below is the PowerShell script that will implement backup/restore procedures for each database which we want to migrate to complete the migration :

#region Load Assemblies and Global Error Handling
[System.Reflection.Assembly]::LoadWithPartialName( `
	"Microsoft.SqlServer.SMO") | Out-Null;
[System.Reflection.Assembly]::LoadWithPartialName( `
	"Microsoft.SqlServer.SMOExtended") | Out-Null;

# Simple global exception handling to see SQL Server errors
trap {
		$Exc = $_.Exception;
		while ( $Exc.InnerException )
		{
			$Exc = $Exc.InnerException;
			Write-Warning ("(generic trap) " + $Exc.Message);
		};
		break;
};
#endregion

#region Event Handlers
$PercentCompleteHandler = `
	[Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] `
	{ 
		Write-Host ([string]$_.Percent + " percent processed.");
	};
$CompleteHandler = `
	[Microsoft.SqlServer.Management.Common.ServerMessageEventHandler] `
	{
		Write-Host $_.Error.Message;
	};
#endregion

#region Functions definition
function Get-SQLInstance($InstanceName, $Login, $Password)
{
	$SQLInstance = New-Object "Microsoft.SqlServer.Management.Smo.Server" `
							  $InstanceName;
	if ($Login -eq $null) {
		$SQLInstance.ConnectionContext.LoginSecure = $true;
	}
	else {
		$SQLInstance.ConnectionContext.LoginSecure = $false;
		$SQLInstance.ConnectionContext.Login = $Login;
		$SQLInstance.ConnectionContext.Password = $Password;
	};
	# Force connection to get an early error message
	$SQLInstance.ConnectionContext.Connect();
	return $SQLInstance;
};
function DatabaseFullBackup ($SQLInstance, $DatabaseName, $BackupPath)
{
	$Backup = New-Object "Microsoft.SqlServer.Management.Smo.Backup";
	$Backup.Action = "Database";
	$Backup.Database = $DatabaseName;
	$Backup.Initialize = $true;
	$Backup.CopyOnly = $true;
	$Backup.Devices.AddDevice($BackupPath + "\" + $DatabaseName + ".bak" `
								, "File");

	$Backup.add_PercentComplete($PercentCompleteHandler);
	$Backup.add_Complete($CompleteHandler);

	$Backup.SqlBackup($SQLInstance)
};
function RestoreDatabaseFromFullBackup ($DestinationSQLInstance, $DatabaseName `
								, $BackupPath, $DataFilesPath, $LogFilesPath)
{
	$Restore = New-Object "Microsoft.SqlServer.Management.Smo.Restore";
	$Restore.FileNumber = 1;
	$Restore.Devices.AddDevice($BackupPath + "\" + $DatabaseName + ".bak"`
								, "File");

	foreach ($File in $Restore.ReadFileList($DestinationSQLInstance))
	{
		$NewFile = New-Object "Microsoft.SqlServer.Management.Smo.relocatefile";
		$NewFile.LogicalFileName = $File.LogicalName;
		
		#Primary Data File
		if	($File.FileID -eq 1 -and $DataFilesPath -ne "")
		{	
			$NewFile.PhysicalFileName = ($DataFilesPath + "\" + $DatabaseName `
											+ "_" + $File.LogicalName + ".mdf");
		}
		#Secondary Data File
		elseif	($File.Type -eq "D" -and $DataFilesPath -ne "")
		{	   
			$NewFile.PhysicalFileName = ($DataFilesPath + "\" + $DatabaseName`
											+ "_" + $File.LogicalName + ".ndf");
		}
		#Log File
		elseif	($File.Type -eq "L" -and $LogFilesPath -ne "")
		{
			$NewFile.PhysicalFileName = ($LogFilesPath + "\" + $DatabaseName `
											+ "_" + $File.LogicalName + ".ldf");
		};

		if ($NewFile.PhysicalFileName -ne $null) {
			[void]$Restore.RelocateFiles.add($Newfile);
		};
	};
	
	$Restore.Database = $DatabaseName;
	$Restore.ReplaceDatabase = $true;
	$Restore.NoRecovery = $false;
	$Restore.Action = "Database";

	$Restore.add_PercentComplete($PercentCompleteHandler);
	$Restore.add_Complete($CompleteHandler);

	$Restore.SqlRestore($DestinationSQLInstance); 
};
#endregion

#region Main
#Parameters
$SourceSQLInstanceName = "DESKTOP-02JIB76";                    # Mention your Source Instance Name 
$DestinationSQLInstanceName = "DESKTOP-02JIB76\INS17";         # Mention your Destination InstanceName

$BackupPath = "E:\Backup\INS17\";                              # Mention your Backup Path which can be your Local Path or Shared Path

$DataFilesPath = "D:\INS17\DATA";                              # Mention your Destination DATA File Path
$LogFilesPath = "D:\INS17\LOG";                                # Mention your Destination LOG File Path

$DatabaseNames = "BLOB","panda","dbareports";                  # Mention your Databases Names which are needed to Migrate

#Main
$SourceSQLInstance = Get-SQLInstance $SourceSQLInstanceName;
$DestinationSQLInstance = Get-SQLInstance $DestinationSQLInstanceName;

foreach ($DatabaseName in $DatabaseNames)
{
	Write-Host ("`nBackup database [" + $DatabaseName + "]");
	DatabaseFullBackup 	$SourceSQLInstance $DatabaseName $BackupPath;

	Write-Host ("`nRestore database [" + $DatabaseName + "]");
	RestoreDatabaseFromFullBackup 	$DestinationSQLInstance $DatabaseName `
									$BackupPath $DataFilesPath $LogFilesPath;

};
#endregion

You’ll need to update a few parameters in the script above, such as SourceInstanceName, Destination Instance Name, Backup Path, DATA File Path, LOG File Path and the Databases Names .

Once all of the parameters have been adjusted to your environment, the script will begin taking database backups from the source instance and restoring them to destination instance.

You can see below snippet where I don;t have any backup files , any Data and Log files:

Also I don’t have any Databases in my Destination Instance.

Now I’m backing up and restoring my “BLOB”,”panda”,”dbareports” databases with the PowerShell Script above. When I run the script, it will back up the first database, restore it to the Destination Instance after the backup is complete, and then take backups for the second database, It will begin restoring after the backup has been completed.

You can see in above Screenshot when Panda Database backup completed immediately it start s to Restore Panda Database in Destination , once the restore completed it will start backup for next Database (dbareports database) and will restore

The script completed migration of databases which I mentioned the DatabasesField

All three databases have been successfully migrated from the Source Instance to the Destination Instance. Now all you have to do is run the script in PowerShell ISE and it will take care of migrating your provided databases.

Starting and Stopping All SQL Server services on a server with PowerShell

Suddenly, I received a request to shut down a number of SQL Server instances in order to relieve some load. A lot is defined as 60 or more instances spread across 30 servers.

Manually logging onto each server and stopping services is a massive chore, especially because some servers have numerous instances. So I decided to go with a powershell script to automate the process.

PowerShell has two important cmdlets: stop-service and start-service. I’m sure I don’t have to go into great detail about what each one does! They don’t, however, accept a remote computer option, and while you could use them in conjunction with the invoke-command cmdlet to perform true remoting, this isn’t available on many of our servers.

In addition, the script must shut down all SqL services, including the SQL Engine, SQL Agent, SSIS, SSAS, and SSRS, among others.

The PowerShell script below creates two functions: one to stop all SQL services and the other to start them all. However, it stops and starts all SQL services, but some of them throw an error; even then, the script does not stop; instead, it moves on to the next service to perform the requested operation.

PowerShell is used for automation and configuration management framework. As PowerShell is available for Linux platforms, you can subsequently use it to start and stop SQL Server services on both Windows and Linux computers. Keep in mind that PowerShell Core is still in beta, so the code below used may or may not work on Linux machines.

The Get-Service cmdlet can be used to view service status in PowerShell by giving the service name in the –Name parameter. The following is the syntax for viewing the default SQL Server instance’s service status:

Get-Service -Name MSSQLSERVER

We may use the Set-Service cmdlet with the following parameters to start or stop a service using PowerShell:

Set-Service -Name MSSQLSERVER -Status Running -PassThru

where -Name Parameter is Providing ‘InstanceName’, Status Parameter is for the service’s expected state We must provide Running for the –Status argument if we want to start the service and Stopped if we want it to stop, -PassThru Parameter is to display the Output of the given command in the console .

Function to Create Stop All SQL Related services on a Machine :

#Stops all SQL Server services on a specific server with this function.
# Stop-AllSQLServerServices Node1 
function Stop-AllSQLServerServices
{
    [cmdletbinding()]
    Param([string]$Server
    , [bool]$StopSQL=$true
    , [bool]$StopAgent=$true
    , [bool]$StopSSRS=$true
    , [bool]$StopBrowser=$true
    , [bool]$StopSSIS=$true
    , [bool]$StopTextDaemon=$true
    , [bool]$StopSSAS=$true)
 
    #Get all the services on the server
    $Services = get-service -ComputerName $Server
 
    if($StopAgent -eq $true)
    {
        #check the SQL Server Agent services
        write-verbose "Checking Agent Services"
 
        #get all named agent instances and the default instance
        ForEach ($SQLAgentService in $Services | where-object {$_.Name -match "SQLSERVERAGENT" -or $_.Name -like "SQLAgent$*"})
        {
            #check the servcie running status
            if($SQLAgentService.status -eq "Running")
            {
                #if stopped, start the agent
                write-verbose "Stopping SQL Server Agent $($SQLAgentService.Name)"
                $SQLAgentService.Stop()
            }
            else
            {
                #write comfort message that the service is already running
                write-verbose "SQL Agent Service $($SQLAgentService.Name) is already stopped."
            }
        }
    }
    else
    {
        write-verbose "Skipping checking Agent services"
    }
 
    if($StopSSRS -eq $true)
    {
        #check the SSRS services
        write-verbose "Checking SSRS Services"
 
        #get all reporting service services
        ForEach ($SSRSService in $Services | where-object {$_.Name -match "ReportServer"})
        {
            #check the status of the service
            if($SSRSService.status -eq "Running")
            {
                #if stopped, start the agent
                write-verbose "Stopping SSRS Service $($SSRSService.Name)"
                $SSRSService.Stop()
            }
            else
            {
                #write comfort message that the service is already running
                write-verbose "SSRS Service $($SSRSService.Name) is already stopped."
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SSRS services"
    }
 
    if($StopSSIS -eq $True)
    {
 
        #get the SSIS service (should only be one)
        write-verbose "Checking SSIS Service"
 
        #get all services, even though there should only be one
        ForEach ($SSISService in $Services | where-object {$_.Name -match "MsDtsServer*"})
        {
            #check the status of the service
            if($SSISService.Status -eq "Running")
            {
                #if its stopped, start it
                write-verbose "Stopping SSIS Service $($SSISService.Name)"
                $SSISService.Stop()
            }
            else
            {
                #write comfort message
                write-verbose "SSIS $($SSISService.Name) already stopped"
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SSIS services"
    }
 
    if ($StopBrowser -eq $true)
    {
 
        #Check the browser, start it if there are named instances on the box
        write-verbose "Checking SQL Browser service"
 
        #get the browser service
        $BrowserService = $services | where-object {$_.Name -eq "SQLBrowser"}
 
        if($BrowserService.Status -eq "Running")
        {
            #if its stopped start it
            write-verbose "Stopping Browser Server $($BrowserService.Name)"
            $BrowserService.Stop()
        }
        else
        {
            #write comfort message
            write-verbose "Browser service $($BrowserService.Name) is already stopped"
        }
    }
    else
    {
        write-verbose "Skipping checking Browser service"
    }
 
    if($StopTextDaemon -eq $True)
    {
 
        # Start the full text daemons
        write-verbose "Checking SQL Full Text Daemons"
 
        ForEach($TextService in $Services | where-object {$_.Name -match "MSSQLFDLauncher"})
        {
            #check the service status
            if ($TextService.Status -eq "Running")
            {
                #start the service
                write-verbose "Stopping Full Text Service $($TextService.Name)"
                $TextService.Stop()
            }
            else
            {
                write-verbose "Text service $($TextService.Name) is already stopped."
            }
        }
    }
    else
    {
        write-verbose "Skipping checking Text Daemon services"
    }
 
    if($StopSSAS -eq $True)
    {
 
        # start the SSAS service
        write-verbose "Checking SSAS services"
 
        ForEach($SSASService in $Services | where-object {$_.Name -match "MSSQLServerOLAP"})
        {
            #check the service status
            if ($SSASService.Status -eq "Running")
            {
                #start the service
                Write-verbose "Stopping SSAS Service $($SSASService.Name)"
                $SSASService.Stop()
            }
            else
            {
                write-verbose "SSAS Service $($SSASService.Name) is already stopped."
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SSAS services"
    }
 
     if($StopSQL -eq $true)
    {
        #check the SQL Server Engine services
        write-verbose "Checking SQL Server Engine Services"
 
        #get all named instances and the default instance
        foreach ($SQLService in $Services | where-object {$_.Name -match "MSSQLSERVER" -or $_.Name -like "MSSQL$*"})
        {
            #Check the service running status
            if($SQLService.status -eq "Running")
            {
                #if stopped start the SQL Server service
                write-verbose "Stoppin SQL Server Service $($SQLService.Name)"
                $SQLService.Stop()
            }
            else
            {
                #Write comfort message that the service is already running
                write-verbose "SQL Server Service $($SQLService.Name) is already stopped"
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SQL Engine services"
    }
 
}

I used PowerShell to run the Stop function, which stopped almost all services except for one, as shown in the output:

Function to Create Start All SQL Related services on a Machine :

#All of the SQL Server services on a specific server are started with this function.
# Start-AllSQLServerServices Node1
 
function Start-AllSQLServerServices
{
    [cmdletbinding()]
    Param([string]$Server
    , [bool]$StartSQL=$true
    , [bool]$StartAgent=$true
    , [bool]$StartSSRS=$true
    , [bool]$StartBrowser=$true
    , [bool]$StartSSIS=$true
    , [bool]$StartTextDaemon=$true
    , [bool]$StartSSAS=$true)
 
    #Get all the services on the server
    $Services = get-service -ComputerName $Server
 
    if($StartSQL -eq $true)
    {
        #check the SQL Server Engine services
        write-verbose "Checking SQL Server Engine Services"
 
        #get all named instances and the default instance
        foreach ($SQLService in $Services | where-object {$_.Name -match "MSSQLSERVER" -or $_.Name -like "MSSQL$*"})
        {
            #Check the service running status
            if($SQLService.status -eq "Stopped")
            {
                #if stopped start the SQL Server service
                write-verbose "Starting SQL Server Service $($SQLService.Name)"
                $SQLService.Start()
            }
            else
            {
                #Write comfort message that the service is already running
                write-verbose "SQL Server Service $($SQLService.Name) already running"
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SQL Engine services"
    }
 
    if($StartAgent -eq $true)
    {
        #check the SQL Server Agent services
        write-verbose "Checking Agent Services"
 
        #get all named agent instances and the default instance
        ForEach ($SQLAgentService in $Services | where-object {$_.Name -match "SQLSERVERAGENT" -or $_.Name -like "SQLAgent$*"})
        {
            #check the servcie running status
            if($SQLAgentService.status -eq "Stopped")
            {
                #if stopped, start the agent
                write-verbose "Starting SQL Server Agent $($SQLAgentService.Name)"
                $SQLAgentService.Start()
            }
            else
            {
                #write comfort message that the service is already running
                write-verbose "SQL Agent Service $($SQLAgentService.Name) already running"
            }
        }
    }
    else
    {
        write-verbose "Skipping checking Agent services"
    }
 
    if($StartSSRS -eq $true)
    {
        #check the SSRS services
        write-verbose "Checking SSRS Services"
 
        #get all reporting service services
        ForEach ($SSRSService in $Services | where-object {$_.Name -match "ReportServer"})
        {
            #check the status of the service
            if($SSRSService.status -eq "Stopped")
            {
                #if stopped, start the agent
                write-verbose "Starting SSRS Service $($SSRSService.Name)"
                $SSRSService.Start()
            }
            else
            {
                #write comfort message that the service is already running
                write-verbose "SQL Agent Service $($SSRSService.Name) already running"
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SSRS services"
    }
 
    if($StartSSIS -eq $True)
    {
 
        #get the SSIS service (should only be one)
        write-verbose "Checking SSIS Service"
 
        #get all services, even though there should only be one
        ForEach ($SSISService in $Services | where-object {$_.Name -match "MsDtsServer*"})
        {
            #check the status of the service
            if($SSISService.Status -eq "Stopped")
            {
                #if its stopped, start it
                write-verbose "Starting SSIS Service $($SSISService.Name)"
                $SSISService.Start()
            }
            else
            {
                #write comfort message
                write-verbose "SSIS $($SSISService.Name) already running"
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SSIS services"
    }
 
    if ($StartBrowser -eq $true)
    {
 
        #Check the browser, start it if there are named instances on the box
        write-verbose "Checking SQL Browser service"
 
        #check if there are named services
        if(($services.name -like "MSSQL$*") -ne $null)
        {
            #get the browser service
            $BrowserService = $services | where-object {$_.Name -eq "SQLBrowser"}
 
            if($BrowserService.Status -eq "Stopped")
            {
                #if its stopped start it
                write-verbose "Starting Browser Server $($BrowserService.Name)"
                $BrowserService.Start()
            }
            else
            {
                #write comfort message
                write-verbose "Browser service $($BrowserService.Name) already running"
            }
        }
        else
        {
            #if no named instances, we don't care about the browser
            write-verbose "No named instances so ignoring Browser"
        }
    }
    else
    {
        write-verbose "Skipping checking Browser service"
    }
 
    if($StartTextDaemon -eq $True)
    {
 
        # Start the full text daemons
        write-verbose "Checking SQL Full Text Daemons"
 
        ForEach($TextService in $Services | where-object {$_.Name -match "MSSQLFDLauncher"})
        {
            #check the service status
            if ($TextService.Status -eq "Stopped")
            {
                #start the service
                write-verbose "Starting Full Text Service $($TextService.Name)"
                $TextService.Start()
            }
            else
            {
                write-verbose "Text service $($TextService.Name) already running."
            }
        }
    }
    else
    {
        write-verbose "Skipping checking Text Daemon services"
    }
 
    if($StartSSAS -eq $True)
    {
 
        # start the SSAS service
        write-verbose "Checking SSAS services"
 
        ForEach($SSASService in $Services | where-object {$_.Name -match "MSSQLServerOLAP"})
        {
            #check the service status
            if ($SSASService.Status -eq "Stopped")
            {
                #start the service
                Write-verbose "Starting SSAS Service $($SSASService.Name)"
                $SSASService.Start()
            }
            else
            {
                write-verbose "SSAS Service $($SSASService.Name) already running."
            }
        }
    }
    else
    {
        write-verbose "Skipping checking SSAS services "
    }
}

I used PowerShell to run the Start function, which started almost all services except some of them, as shown in the output:

We may also accomplish this using DBATOOLS, and the commands are provided below. Before executing these commands, we must first install the DBATOOLS Module.


Get-DbaService

Start-DbaService

Stop-DbaService

Restart-DbaService

Troubleshoot Missing Of MSI or MSP files using FixMissingMSI tool

If you’ve ever had troubles with missing cached MSI/MSP files during SQL server setup, you might be familiar with the following article:
How to fix difficulties that occur during a SQL Server update by restoring the missing Windows Installer cache files.

https://docs.microsoft.com/en-US/troubleshoot/sql/install/restore-missing-windows-installer-cache-files

The above link has a VB script that will assist you in locating lost MSI/MSP files in the Windows installer folder, as well as recovering these files if the setup source is restored. The VB script works fine, however if there are a lot of missing MSI/MSP files, copying them back one by one can be tedious.

FixMissingMSI Tool :

The FixMissingMSI software will be used in this approach to locate MSI and MSP files that are missing from the Windows Installer cache. You can also point the tool to the original media locations and have it recache the missing files as an extreme measure.

The FixMissingMSI software is available for Free download from the below link :

https://github.com/suyouquan/SQLSetupTools/releases/

I extracted the file from the latest version 2.2.1 software that I downloaded from the URL above.

One of the prerequisites for using this tool is that you have.NET Framework 4.5 installed.

After you’ve extracted the downloaded software, navigate to the Manual folder to learn how to use this tool.

When I was installing SQL 2014 Service Pack 3 and Cumulative Update today, I ran into an issue with MSI and MSP files missing. I tried this FixMissingMSI software to see if I had several files missing, and we were able to fix them using this tool.

When I double-clicked FixMissingMSI.exe, a wizard appeared, asking if I wanted to set up the scan menu.
If you select “Product name contains” and enter “SQL,” the program will search for all products whose product names contain the key word and also you need to provide Media + SP + CU location path

If you specify this setup source folder, this program will search all of the *.MSI and *.MSP files inside to see if any missing or mismatched MSI/MSPs can be identified.
If you don’t specify this folder, the tool may be unable to locate the MSI/MSP for those missing/mismatched files, leaving you unable to repair them. Even if you don’t specify this path, this program may still be able to locate the missing MSI/MSP in the installed product’s LastUsedSource folder.
For example, for the SQL product, the best practice is to place the SQL server RTM setup media and all subsequent service packs, CUs in the same folder, for example:

Please remember to extract the package using the ‘X‘ switch to the folder if you download service packs or cumulative updates from the Microsoft site. For instance, the command below extracts SP1 to the SP1 subfolder:


SQLServer2014SP3-KB4022619-x64-ENU.exe /X


Even though the package is in the same folder, it is useless if you do not extract it.

I’ve created a media path that includes RTM, SP, and CU. Clicked SCAN NOW button

If you have any missing files, the scanning results will show them like below :

You will see all files in the All option, which signifies the status of Missing, Mismatched, and OK.
Only those will be listed if you pick Missing or Mismatched only.

When I selected Fix It, a pop-up window appeared, instructing me to click OK to copy the missing file.

It was fixed by copying the file from Install Source to Installer Folder after pressing the Fix It button, and that line was marked as GREEN.

We can fix the missing msi files separately, as shown above, however fixing the number of multiple files individually is a time-consuming operation. So, we can accomplish it by going to the Fix TAB and clicking on the Fix All button.

As you can see, I have 60 missing files that need to be restored to the Installer folder on Drive C. When I clicked the Fix All option, a pop window appeared asking me to click OK to immediately fix all missing files. I pressed the OK button.

It repaired 30 missing files and attempted to install SQL 2014 SP3 and CU, which it did successfully.

There are still 30 files that need to be repaired. Here’s what I noticed from the tool, This FixmissingMSI tool has a column called ‘LastUsedSource,’ which is nothing but the location where we installed the most recent SP or CU. If the setup folder exists on the server, this tool will automatically gather information from that LastUsedSource, which is nothing more than the Last Installed Source location of the media, service pack, or cumulative update.

It will not do anything if the recently installed SP or CU folders do not exist on the server, and the column ‘Fixcommand’ will not be generated with any commands to repair it.

I‘m not sure if my assumption is correct.

As a report, we can also export the data from the missing files to a CSV and text file.

When you are exporting the data out from File TAB and clicking on Export just provide the Filename and click ok
Two Files with format .csv and .txt are automatically created on the physical location where you have given path to store with Filename which you have given .

Note :

The SQL Media\Service Pack \ Security Update \ Cumulative Update We must manually extract any patch or ISO file to a specific directory or folder before running the installation by double-clicking the “SETUP.exe” file, which is Best Practice for Installation.
If we launch the package without first manually extracting it, the software will extract it to an unknown location and begin the setup process. When the server is REBOOTED, that UN-known location may no longer exist on the server, and the next time we run any New SP\CU\SU, it will check for previously extracted locations, but if that place is not present on the server, an error will be thrown, and the installation will fail.