Speeding up a powershell script

I need to validate that the Exchange Cloud accounts are valid.
So I can get the cloud accounts with $list_CloudUsers.
Next I need to validate that each of the cloud accounts are not disabled in ActiveDirectory. So I have the FOR loop.

Getting the $list_CloudUsers takes about 10 minutes which is fine but the FOR loop takes over an hour to complete.
How can I speed up the FOR loop.
Can I put it into a single line , like I did for $list_CloudUsers ?

$list_CloudUsers = Get-Recipient -ResultSize Unlimited | Where { $_.RecipientTypeDetails -like “*RemoteUserMailbox”}
$list_CloudUsers = $list_CloudUsers | ConvertTo-Csv | select -skip 2  |  % {$_.Replace('","',';')} |% {$_.Replace('"','')}

foreach ($item in $list_CloudUsers) 
        {
        $alias = ($item -split ";")[0]
        $SamAccountName = (Get-Recipient $alias).SamAccountName
        $Ad_Enabled = (Get-ADUser $SamAccountName).Enabled
        if ($Ad_Enabled -like "False"){Continue}
        $item >> "c:\temp\user_list.txt"
        }

Thanks Hil

Since you’re filtering to only collect mailboxes, you could try Get-Mailbox rather than Get-Recipient in your first line. This should speed up the collection process a little bit as it will not have to comb through contacts and other recipient types.

Did you have a particular reason for converting your variable of objects to CSV? It would be much simpler to use the objects that are stored in your $list_CloudUsers variable.

Example might looks something like:

#Collect the mailboxes
$list_CloudUsers = Get-Mailbox -ResultSize Unlimited | Where { $_.RecipientTypeDetails -like “*RemoteUserMailbox”}

#Capture the mailboxes with a Disabled AD account into Results variable
$results = foreach ($item in $list_CloudUsers) {
    if ((Get-ADUser $item.SamAccountName).enabled -eq $false) {$item}
    }

#Output your results to a CSV with your desired properties selected    
$results | select samaccountname,name,primarysmtpaddress | Export-Csv C:\temp\user_list.csv -NoTypeInformation

Thank you. That works Great !!!
The For loop is down to 5 minutes.

How about using a Workflow…I’ve not tested this so beware…but if you can use a Workflow it’ll be much faster.

#Collect the mailboxes
$list_CloudUsers = Get-Mailbox -ResultSize Unlimited | Where { $_.RecipientTypeDetails -like “*RemoteUserMailbox”}

workflow Get-CloudUsers {
    param(
        [string]$users
        )
          
    foreach -parallel($item in $users)
       {
             InLineScript  {
                if ((Get-ADUser $item.SamAccountName).enabled -eq $false) 
                {$item}
                }
            
        }         
} 

$results = Get-CloudUsers $list_CloudUsers 
$results | select samaccountname,name,primarysmtpaddress | Export-Csv C:\temp\user_list.csv -NoTypeInformation

Hi Iain, I just tried the workflow script and it gives me the following error:
Missing opening ‘(’ after keyword ‘foreach’.
Tried couple variations… same thing