Functions/Wait-BcServerInstanceMountingTenants.ps1


<#
.SYNOPSIS
    Waits for the the Service Instance to mount all attached tenants and executes Get-NavTenant in ForceSync mode.
.DESCRIPTION
    After a restart from a multi-tenant Business Central ServerTier it can take a while to mount each tenant.
    This function waits for all tenants to be mounted and performs a Get-NavTenant in ForceSync mode to get the tenant from mounted to operational.
.EXAMPLE
    Wait-BcServerInstanceMountingTenants -ServerInstance $ServerInstance
#>


function Wait-BcServerInstanceMountingTenants{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        $ServerInstance
    )
    $Mounting = $false
    while($Mounting -eq $false){

        $Tenants = Get-NAVTenant -ServerInstance $ServerInstance

        if('Mounting' -in $Tenants.State){
            'Waiting for tenant(s) to be mounted on ServerInstance {0}.' -f $ServerInstance | Write-Host
            Start-Sleep -Seconds 10  
        } else {
            'Tenant(s) mounted on ServerInstance {0}.' -f $ServerInstance | Write-Host
            $Mounting = $true
        }   
    }
    # Invoke Get-NAVTenant with ForceRefresh to bring the tenants from state 'Mounted' to 'Operational'.
    (Get-NAVTenant -ServerInstance $ServerInstance).Id | ForEach-Object {
        Get-NAVTenant -ServerInstance $ServerInstance -Tenant $_ -ForceRefresh
    }
}

Export-ModuleMember -Function Wait-BcServerInstanceMountingTenants