PowerShell – update SQL Server

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

#-------------[deklarations]--------------------------
#source
$computers=Get-Content '\\host\shares\!scripts\!source\!computers.txt'
#logs
$successLog='\\host\shares\!scripts\!logs\done.LOG'
$errorLog='\\host\shares\!scripts\!logs\error.LOG'
$unreachableLog='\\host\shares\!scripts\!logs\unreachable.LOG'
#params
$source='\\host\shares\!install\sql\'
$destination='c$\install\sql\'
#-------------[functions]--------------------------
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 {
            $sqlVersion=getSQLVersion($computer)
            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
    }
}
#-------------krolaki.eu--------------------------

 

Leave a Reply

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