WorkWithDistributionGroupPermissions.ps1
#WorkwithDistributionGroupPermissions.ps1 / rb / 2020
#adde oder entferne einen Benutzer an einer Exchange-Verteilerliste
 
# erforderliche Resourcenoptionen:
# $username # wird immer von Tenfold mitgeliefert
# $cred # konfigurierte Zugangsdaten für den Exchangeserver
# $connectionUri # z.B. "https://myexchangesrv/PowerShell"
# $dgname # einfacher Name der Verteilergruppe z.B. "ABTEILUNG1"
# erforderliche Resourcenbedingungen:
# "Resource - New"
# "Resource - Delete"
##############################################################
$username = $params.request.person.masterdata.userName
$connectionUri = $params.connectionUri
$dgname = $params.dgname
 
if(!($session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectionUri -Authentication Basic -Credential $cred))
{
    return "Failed to create remote PowerShell session to "
    exit 
}
 
Import-PSSession $session -AllowClobber -DisableNameChecking
Import-module ActiveDirectory -DisableNameChecking
 
 
$displayname = Get-ADUser $username | select -expand Name
 
 
$status = Get-DistributionGroupMember -Identity $dgname | where {$_.name -like "$displayname"}
if ($status) { 
        try   {
                Remove-DistributionGroupMember -Identity $dgname -Member $username -Confirm:$false
              }
        catch {
        	Remove-PSSession $session
                return "error: $username could not be removed from Distributionlist $dgname";
                exit 1;
              }
 
 
}
 else {  
        try   {
              Add-DistributionGroupMember -Identity $dgname -Member $username -Confirm:$false
              }
        catch {
                Remove-PSSession $session
                return "error: $username could not add to Distributionlist $dgname";
                exit 1;
              }
 
 }
 Remove-PSSession $session
 
#############################################################