Speeding up large query

Hello Everyone,
I have a PowerShell query as part of a script I fairly often to track my enterprise’s users MFA status. It’s pretty slow and I wanted to see if there was anything I could tweak to speed it up.

Here is the portion of the script that takes forever. Last time I ran Measure-Command it was over 10 minutes.

First it looks for All users in Azure that are Enabled Users that have some form of Exchange licensed on their account.

Then I use regex for the second variable to only return users who’s UPN starts with a 0,4,8 and the UPN is 7 digits long.

$ExportUsers = Get-MsolUser -EnabledFilter EnabledOnly -All | Where-Object {$_.Licenses.ServiceStatus | Where-Object {(($_.ServicePlan.ServiceName -eq "EXCHANGE_S_ENTERPRISE") -or ($_.ServicePlan.ServiceName -eq "EXCHANGE_S_STANDARD") -or ($_.ServicePlan.ServiceName -eq "EXCHANGE_S_DESKLESS")) -and $_.ProvisioningStatus -eq "Success"}}

$AllUsers = $ExportUsers | Where-Object {$_.UserPrincipalName -match "^[048]\d{6}"}

Is there a better way to arrange the “Wheres” or a better filtering I could do to possibly speed this up?
It’s roughly 24,000 users this script runs through.

Thanks for your help,
Rob Martin

I dont have an Azure environment to test this and not sure if the ‘SearchString’ parameter accepts your UPN string format. If not, Where-Object would have to be used.

# Get users with UPN match for displayname/email and have a license
$exportuser = (Get-MsolUser -SearchString "^[048]\d{6}" -EnabledFilter EnabledOnly -All).Where({$_.isLicensed -eq $true})

# Filter those UPN users
($exportuser).Where({
$_.ServicePlan.ServiceName -match 'EXCHANGE_S_ENTERPRISE|EXCHANGE_S_STANDARD|EXCHANGE_S_DESKLESS' -AND $_.ProvisioningStatus -eq 'Success'
})