PowerShell – update SQL Server

A method for installation Microsoft SQL Server 2008R2 SP3, or KB2979597.

$computers=Get-Content '\\host\shares\!scripts\!source\!computers.txt'
function getSqlVersion {
    param ( 
        [string] $computer)
    $sqlVersion=Invoke-Command -ComputerName $computer -ScriptBlock {Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\SQLEXPRESS\MSSQLServer\CurrentVersion\'}
    return $sqlVersion.CurrentVersion

foreach($computer in $computers) {
    if(Test-Connection -ComputerName $computer -Count 1 -Quiet) {
        Try {
            if($sqlVersion.Equals('10.50.4000.0')) {
                Invoke-Expression "msg.exe * /SERVER:$computer /TIME:3600 'Do not shut down the computer - update in progress!'"

                Write-host "Copying files: $computer" -foreground 'gray'
                Copy-Item -Path $source -Destination \\$computer\$destination -Force -Recurse
                Write-host "Installation: $computer" -foreground 'gray'   
                Invoke-Command -ComputerName $computer -ScriptBlock {powershell.exe 'c:\install\sql\SQLServer2008R2SP3-KB2979597-x86-ENU.exe' /Quiet /IAcceptSQLServerLicenseTerms /Action=Patch /AllInstances}

                Invoke-Expression "msg.exe * /SERVER:$computer /TIME:21600 'Computer has been updated - please restart it, otherwise authomatic restart will take place in 6 hours.'"
                Invoke-Expression "shutdown /m $computer /r /f /c 'Restart' /t 21600"
                Write-host "updated: $computer" -foreground 'green'
                $computer >> $successLog
            } else {
                Write-host "$computer':' $sqlVersion" -foreground 'green'
                $computer + ": " + $sqlVersion >> $successLog
        } Catch {
            Write-host "error: $computer" -foreground 'red'
            $computer >> $errorLog
    } else {
        Write-host "offline: $computer" -foreground 'yellow'
        $computer >> $unreachableLog


Leave a Reply

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