Skip to content

Patch a SQL Server instance automatically with PowerShell

In my last blog post I explained how to automatically download the last Service Pack and Cumulative Update for all versions of SQL Server.
Here I will show you how to patch your SQL Server instances automatically with some cmdlets from the dbatools.

First we need a SQL Credential to be able to remotely connect to the server where we will patch our instances:

$OScred = Get-Credential;

Once done we will have to find the instances located on the server. Here multiple possibilities:

  • you can create just a list with your instances $InstanceList = @(‘Thor90\SQL19_1′,’Thor91\SQL19_1’);
  • you can search the instance on your server with $InstanceList = Get-DbaService | where-object { $_.ServiceType -eq ‘Engine’ -and $_.State -eq ‘Running’ };
  • you can also select your instance in your CMS with $InstanceList = Get-DbaRegServer -SqlInstance ‘Thor90\CMS’ -Group “Prod\SQL2019”; (my case)

Now that we have our list of instances, we will loop on those instances, run a quick connection test and if it succeeds patch our instance.
To patch the instance, I will use 2 dbatools cmdlets which are:

  • Get-DbaBuildReference: will return information about the instance like the SP, CU and used with the -Update switch will update the local reference with the most up to date one
  • Update_DbaInstance: will start a process which will update a SQL Server instance to a specified version
    This cmdlet is really powerful with lots of parameter, possible options and also risks, I let you go through its definition.
    I will use it in my example with the -version parameter which is the target version I want to reach, with the switch -Restart to automatically restart my server after the installation, the parameter -Path to specif the location where my patches have been downloaded, the -Credential to have permission to log remotely to my server and -Confirm to false to run without confirmation.

I’ll use also some logging cmdlets wrote by myself which are Out-Log, Add-Warning and Add-Error.

Questions about your own setup? A dbi services consultant can look at your case.

Talk to an expert (opens in a new tab)

The loop on all my instance list will look like:

ForEach ($Instance in $InstanceList){
     Out-Log -Message "Patching instance $($Instance.InstanceName)" -LogFile $LogFile
        
    $connection = Test-DBAConnection -SqlInstance $instance.InstanceName -WarningVariable warningvar;
    Add-Warning -Warning $Warningvar;
    If ($connection -and $connection.ConnectSuccess) {
        Out-Log -Message "Connection to instance $($Instance.InstanceName) succeeded" -LogFile $LogFile

        #Update the instance build which is used by the cmdlet Update-DbaInstance
        Out-Log -Message "Update the build of the instance $($Instance.InstanceName)" -LogFile $LogFile
        Get-DbaBuildReference -SqlInstance $instance.InstanceName -Update -WarningVariable warningvar;
        Add-Warning -Warning $Warningvar;

        Out-Log -Message "Start patching of the instance $Instance.InstanceName" -LogFile $LogFile
        try {
            $res = Update-DbaInstance -ComputerName $Instance.ComputerName -InstanceName $Instance.InstanceName -credential $OScred -Version CU16 -Path \\Thor90\sources\SQL2019 -Restart -Confirm:$false -WarningVariable warningvar;
            Add-Warning -Warning $Warningvar;
        }
        catch {
            Add-Error -Message "Patching of the instance $instance$Instance.InstanceName not possible, Exception: $($error[0].Exception.Message)";
        }

    }
    Else {
        Add-Error -Message "Impossible to connect to the instance $instance$Instance.InstanceName.";
    }
}

This script will patch my production SQL Server 2019 instances to CU16 with the KB located on my share drive \\Thor90\sources\SQL2019 and restart the server once succeeded.
Lots of scenario can be covered by using this cmdlet, I let you playing with it, but on your test environment first 😉

Let’s work together

Ready to operate at
the next level?

Tell us about your challenge. We’ll bring the depth, the expertise, and the Swiss precision.

Stéphane Savorgnano

Stéphane Savorgnano

Stéphane Savorgnano has more than 20 years of experience in Microsoft software development and SQL Server database solutions, specializing in SQL Server installation, performance analysis, and best practices. He holds Microsoft Certified Solutions Associate (MCSA) and Expert (MCSE) for SQL Server 2012 through 2017, MCTS, MCITP for SQL Server 2008, and ITIL V3 Foundation certifications. Prior to dbi services, he was a software engineer at Ciba Specialty Chemicals in Basel. He holds a Master's degree in Informatics from the University of Mulhouse. His industry experience covers banking and financial services, chemicals, and pharmaceuticals.View Author posts

75 posts since November 2012

Most read in Database

The Database posts our readers open most: the all-time favourites, and what is trending right now.

6 thoughts on “Patch a SQL Server instance automatically with PowerShell”

  1. Russell W Young

    I do not know how to fix this problem
    [Connect-DbaInstance] Failure | Error connecting to [pbidev]: The certificate chain was issued by an authority that is not trusted

  2. Russell W Young

    I like you script to deploying CU’S but the Test-DBAConnection cannot connect because the certificate chain was issued by an authority that is not trusted and I don’t know how to fix that issue. I can run the Update-DbaInstance cmdlet. I have looked at articles from Microsoft on how to fix the issue but don’t understand why I am not having issues with my other Powershell scripts. I am connecting with an account that is SA on all sql servers.

  3. Stéphane Savorgnano

    It’s some functions I wrote:
    Function Out-Log() {
    param(
    [ValidateSet(‘INFO’,’WARNING’,’ERROR’)]
    [String] $Type = ‘INFO’,
    [String] $Message
    )

    If ($LogTo -match ‘Table’) {
    # To replace single quote in the message
    $oldstr = [char]39; # single quote
    $newstr = [char]34; # double quote
    $Message = $Message -replace $oldstr, $newstr;

    $query = “insert into log.LogInventaire values (‘” + $Type + “‘,'” + (Get-Date -f ‘yyyy-MM-dd HH:mm:ss’) + “‘,'” + $Message + “‘)”;
    Invoke-DbaQuery -SqlInstance $DestinationInstance -Database $DBDestination -Query $query;
    }
    Else {
    ‘[‘+(Get-Date -f ‘yyyy-MM-dd HH:mm:ss’) +’] ‘ + ‘ – [‘ + $Type + ‘] – ‘ + $Message | Out-File -FilePath $LogFile -Append;
    }
    }

    Function Add-Warning() {
    param(
    [String] $Warning
    )
    If ($Warning) {
    Out-Log -Type WARNING -Message $Warning;
    }
    }

    Function Add-Error() {
    param(
    [String] $Message
    )
    Out-Log -Type ERROR -Message $Message;
    }

  4. Excellent post! It definitely will save DBA lots of time. May I ask how the script could find version CU16 “-Version CU16″with provided path “\\Thor90\sources\SQL2019”? Did you create another folder named “CU16” under this path “\\Thor90\sources\SQL2019”?

Leave a Comment

Your email address will not be published. Required fields are marked *