Slow Lookup Even Using new V2 Commands - What am I doing wrong?

Good Morning Everyone,

I’m currently trying to run a little script to find all the users that still have access rights set on them from a migration. I opted to use the new EXO commands in the hope that it would be quicker, but I feel like I did something wrong. Here is the script that I’m running below. Where am I going wrong? Is is the where pipe to clean up the users or the Out-string?

$Mailboxes = Get-EXOMailbox -ResultSize Unlimited
$Mailboxes.count

$i = 0
$A = @()

foreach ($Mailbox in $Mailboxes){
$B = Get-EXOMailboxPermission -Identity $Mailbox.UserPrincipalName | ? User -like *@*
$item = New-Object psobject
$item | Add-Member -type NoteProperty -Name 'Mailbox' -Value $Mailbox.DisplayName
$item | Add-Member -type NoteProperty -Name 'UPN' -Value $Mailbox.UserPrincipalName
$item | Add-Member -type NoteProperty -Name 'Accessing User' -Value $B.User
$item | Add-Member -type NoteProperty -Name 'Access Rights' -Value ($B.AccessRights | Out-String).Trim()
$A += $item
$i++

Write-Progress -activity "Looking up user access" -status "Lookedup: $i of $($Mailboxes.Count)" -percentComplete (($i / $Mailboxes.Count)  * 100)
}

Nothing wrong per se, but the object can built a bit better. If you need the permissions in a string, run this first and wrap it in Measure-Object to see how long the execution is taking. To do the conversion, just copy the calculated expression and do the pipe to Out-String. If you can filter the users at Get-EXOMailboxPermission, it would be more ideal, but the documentation is light and there doesn’t appear to be any wildcard capabilities, so you’re getting ALL permissions and then filtering. Here is a slightly cleaner version:

$Mailboxes = Get-EXOMailbox -ResultSize Unlimited
$Mailboxes.count

$i = 0

$results = foreach ( $Mailbox in $Mailboxes ){
     Get-EXOMailboxPermission -Identity $Mailbox.UserPrincipalName | 
     Where-Object -FilterScript{$_.User -like '*@*'} |
     Select-Object -Property User,
                             AccessRights
                             @{Name='DisplayName';Expression={$Mailbox.DisplayName}},
                             @{Name='UserPrincipalName';Expression={$Mailbox.UserPrincipalName}}

    $i++

    Write-Progress -activity "Looking up user access" -status "Lookedup: $i of $($Mailboxes.Count)" -percentComplete (($i / $Mailboxes.Count)  * 100)
}