PowerShell script to update all CRM organizations to newest version

I recently updated a CRM server to the newest update rollup version, and found afterwards the CRM server was configured to not automatically update all the organizations when update rollups are installed. To handle this post-upgrade situation, I wrote a PowerShell script to automate the update of the organizations rather than manually updating each organization one at a time through the deployment manager user interface.

This PowerShell script retrieves all the organizations, and loops through them one at a time to initiate the update process. The Update-CrmOrganization commandlet starts an asynchronously running operation, and the script takes this into account by polling the CRM for the update operation’s status before moving onto the next organization.

Update times will vary based on the organization’s starting version and database size; I found it generally took anywhere from 10 to 30 minutes per organization.

Add-PSSnapin Microsoft.Crm.PowerShell
$orgs = Get-CrmOrganization
foreach($org in $orgs) {
    # change the version number accordingly to the newest version installed
    if($org.Version -ne "") {
        Write-Host (Get-Date).ToLongTimeString() "Working on" $org.UniqueName
        # Initiate the update. The update is processed asynchronously and the status needs to be checked
        $opid = Update-CrmOrganization -Name $org.UniqueName
        do {
            # retrieve the status of the update
            $opStatus = Get-CrmOperationStatus -OperationId $opid
            if($opStatus.State.ToString() -ne "Completed") {
                Write-Host "In progress, waiting 1 minute before checking again"
                Start-Sleep -Seconds 60
            } else {
                Write-Host "Completed, going to next org"
        } until ($opStatus.State.ToString() -eq "Completed")