# updateCrmOrgs.ps1

function updateCrmOrgs{
  try{
    Add-PSSnapin Microsoft.Crm.Powershell
    $servers=Get-CrmServer
    $highestVersion=($servers.Version|measure-object -Maximum).Maximum
    $lowVersionServers=$servers|?{[version]$_.Version -lt [version]$highestVersion}
    if($lowVersionServers){
      write-warning "Program cannot continue because these servers have NOT been upgraded to version $highestVersion`:`r`n$($lowVersionServers|select FullName,Version)"
    }else{
      $orgsToUpgrade=(Get-CrmOrganization|?{[version]$_.Version -lt [version]$highestVersion}).UniqueName
      if($orgsToUpgrade){
        $orgsToUpgrade|%{Update-CrmOrganization -Name $_}
        $operationIds=(get-crmoperationstatus).Id
        $completed=0
        do{
          $status=$operationIds|%{get-crmoperationstatus -operationid $_}
          $currentCompleted=($status.State -match 'Failed|Completed').count
          if($completed -ne $currentCompleted){
              write-host "$currentCompleted of $($operationIds.count) completed"
          }else{
              write-host '.' -nonewline
          }
          $completed=$currentCompleted
          sleep 1
        } until($completed -eq $operationIds.count)
      }else{
        write-host "All Orgs are already at version $highestVersion" -ForegroundColor Green
      }
    }
    return $true
  }catch{
    write-warning $_
    return $false
  }
}
updateCrmOrgs