Functions/Get-Tenant.ps1

function Get-Tenant {
    trap {Out-Error $_; continue;}
    $allTenants = Get-AzureRmTenant -ErrorAction Stop;

    if ($tenants) {
        $totalNoOfTenants = $tenants.Count;
    }
    else {
        $totalNoOfTenants = $allTenants.Count;
    }

    Add-Log "Total no of tenants to process: $totalNoOfTenants" "tenants";

    $noOfTenantsProcessed = 0;

    foreach ($currentTenant in $allTenants) {
        trap {Out-Error $_; continue;}

        $script:currentTenantId = $currentTenant.TenantId;
        if (!$tenants -or $tenants.Contains($currentTenantId)) {
            Write-Progress -Activity "Cloud scanner progress" -id 1 -CurrentOperation "Scanning Tenant: $currentTenantId" -Status "No of tenants to process: $totalNoOfTenants" -PercentComplete (($noOfTenantsProcessed / $totalNoOfTenants) * 100)

            Set-AzureRmContext -TenantObject $currentTenant | Out-Null

            if (!$sections -or $sections.Contains("ad")) {
                Get-ActiveDirectory;
            }

            Get-Subscription;

            $noOfTenantsProcessed++;
            Add-Log "Finished processing tenant: $currentTenantId" "tenants";
        }
    }

    Add-Log "No of tenants processed: $noOfTenantsProcessed" "tenants";
}