$ExchangeSession = (Get-PSSession | ? {$_.ConfigurationName -eq 'Microsoft.Exchange' -and $_.Availability -eq 'Available'})[0]


$AllMailboxes = Invoke-Command -Session $ExchangeSession -ScriptBlock {
    Get-Mailbox -ResultSize Unlimited | Select-Object Identity,DisplayName,GrantSendOnBehalfTo,MessageCopyForSentAsEnabled,MessageCopyForSendOnBehalfEnabled }


$OutputArray = @()
$MailboxCount = 0
$AllMailboxCount = $AllMailboxes.Count

foreach($Mailbox in $AllMailboxes)
{
    $MailboxCount++
    Write-Progress -PercentComplete (($MailboxCount / $AllMailboxCount) * 100) -Activity $Mailbox.DisplayName

    $FullAccessHash = @{}
    $SendOnBehalfHash = @{}
    $SendAsHash = @{}
    $AllTrustees = @()

    ## Get FullAccess Perms
    Get-MailboxPermission -Identity $Mailbox.Identity | ? {$_.AccessRights -eq 'FullAccess' -and $_.IsInherited -eq $FALSE -and $_.User -notlike "*NotesAd*"} | % {
    
        $FullAccessHash.Add((Get-Recipient $_.User).DisplayName.ToString(), $true)
        $AllTrustees += (Get-Recipient $_.User).DisplayName.ToString()

    }#end mbxperm

    ## Get SendOnBehalfTo Perms
    $Mailbox.GrantSendOnBehalfTo | % {
        
         $SendOnBehalfHash.Add((Get-Recipient $_.Name).DisplayName.ToString(), $true)
         $AllTrustees += (Get-Recipient $_.Name).DisplayName.ToString()

    }#end sendonbehalf

    ## Get SendAs Perms
    <#
    Get-ADPermission -Identity $Mailbox.Identity | ? {$_.IsInherited -eq $FALSE -and $_.ExtendedRights -like "*Send-As*" -and $_.User -notlike "*NT AUTHORITY\SELF*"} | % {
    
        $SendAsHash.Add((Get-Recipient $_.User).DisplayName.ToString(), $true)
        $AllTrustees += (Get-Recipient $_.User).DisplayName.ToString()

    }#end mbxperm
    #>

    foreach($UniqueTrustee in $AllTrustees | Select-Object -Unique)
    {
        $OutputArray += [PSCustomObject]@{
                'Mailbox' = $Mailbox.DisplayName.ToString();
                'Trustee' = $UniqueTrustee;
                'FullAccess' = $FullAccessHash.ContainsKey($UniqueTrustee);
                #'SendAs' = $SendAsHash.ContainsKey($UniqueTrustee);
                'SendOnBehalf' = $SendOnBehalfHash.ContainsKey($UniqueTrustee);
        }#end psobject

    }#end trustee loop

}

$OutputArray | Export-Csv C:\Scripts\Output\SendonBehaft.csv -NoTypeInformation 

