workWithMailboxPermissions.ps1
#WorkwithMailboxpermissions.ps1 / rb / 2020
#adde oder entferne einen Benutzer an einer shared Mailbox
 
# erforderliche Provisioning-Parameter der Resource:
# $username # wird immer von Tenfold mitgeliefert
# $cred # konfigurierte Zugangsdaten für den Exchangeserver
# $connectionUri # z.B. "https://myexchangesrv/PowerShell"
# $mailbox # Name der sharedMailbox
# erforderliche Resourcenbedingungen:
# "Resource - New"
# "Resource - Delete"
##############################################################
 
$username = $params.request.person.masterdata.userName
$connectionUri = $params.connectionUri
$mailbox = $params.mailbox
 
 
if(!($session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectionUri -Authentication Basic -Credential $cred ))
#If ($session.state -ne 'Opened')
{
    return "Failed to create remote PowerShell session to $connectionUri"
    exit
}
 
Import-PSSession $session -AllowClobber
#Import-module ActiveDirectory
 
$status = get-mailboxpermission -identity $mailbox -user $username
if($status.IsValid)
 
{
 #   echo "$username have already access -->remove from mailbox $mailbox"
    try   {
            try { Remove-MailboxPermission -Identity $mailbox -User $username -AccessRights FullAccess,DeleteItem,ReadPermission,ChangePermission -InheritanceType All -confirm:$false }
            catch { return "failed Remove-MailboxPermission $username from $mailbox ";exit; }
            Get-User -identity $mailbox | Remove-ADPermission -user $username -ExtendedRights "Send As" -confirm:$false
          }
    catch { Remove-PSSession $session
    	    return "error: failed to remove permissions of $username from mailbox $mailbox";
            exit;}
 
}
else
{  
#    echo "$username have no rights --> add to mailbox $mailbox"
    try   {
          try { Add-MailboxPermission -Identity $mailbox -User $username -AccessRights FullAccess -InheritanceType All -confirm:$false}
          catch { return "failed Remove-MailboxPermission $username from $mailbox ";exit; }
          Get-User -identity $mailbox | Add-ADPermission -user $username -ExtendedRights "Send As" -confirm:$false
         }
    catch { Remove-PSSession $session
            return "error: failed to remove permissions of $username from mailbox $mailbox";
            exit;
          }
 
 }
 
Remove-PSSession $session
 
exit
 
#############################################################