The below code is trying to remove documents and permission on all shared mailboxes. The below script is taking more time to execute. I want to make the script to execute faster any help will be appreciated.
$AmIOnO365=get-Mailbox -identity $User.UserPrincipalName -erroraction SilentlyContinue
if($AmIOnO365 -ne $null)
{
$SharedMailboxes = Get-Mailbox -ResultSize unlimited -Filter {RecipientTypeDetails -eq 'SharedMailbox'}
#write-host -ForegroundColor Green " All shared mailboxes for full delegation and remove as necessary"
$Full=$null
$Counter=0
$SAM=$null
foreach ($SharedMailbox in $SharedMailboxes)
{
$Counter=$Counter+1
#write-host -ForegroundColor Green $Counter "/" $SharedMailboxes.count"."$SharedMailbox.PrimarySmtpAddress
# Full Access Rights
$Full = Get-MailboxPermission -identity $SharedMailbox.PrimarySmtpAddress | where {$_.IsInherited -eq $False -and $_.User -notlike "NT AUTHORITY*" -and $_.User -notlike "S-1-5-21*" -and $_.User -notlike "NAM*"}
If ($Full)
{
Foreach ($DelegatedUser in $Full)
{
if($DelegatedUser.User -eq $UserPrimarySMTPAddress.PrimarySmtpAddress)
{
$SAM=$DelegatedUser.User
Write-Host -ForegroundColor Yellow " Removed full rights: $SAM on the shared mailbox:"$SharedMailbox.PrimarySmtpAddress
$LogFileContent+="`n`r`n`rRemoved full rights: "+$SAM+" on the shared mailbox: "+$SharedMailbox.PrimarySmtpAddress
#write-host -ForegroundColor White " Removing" $UserPrimarySMTPAddress.PrimarySmtpAddress "rights of" $DelegatedUser.AccessRights "from " $SharedMailbox.PrimarySMTPaddress
Remove-MailboxPermission -Identity $SharedMailbox.PrimarySMTPaddress -user $UserPrimarySMTPAddress.PrimarySmtpAddress -AccessRights $DelegatedUser.AccessRights -Confirm:$False
}
}
}
}
$LogFileContent > $FileName
}