Office Servers and Services

"La connaissance ne vaut que si elle est partagée" / "An effective Knowledge is a shared one"

Délégations de Boîtes aux lettres Exchange Server 2010

Posted by David PEKMEZ sur août 29, 2011


Bonjour,

Je vous présente un script qui pourrait vous dépanner lors de demandes de délégations sur un environnement Exchange Server 2010, lors d’une migration ou simplement en administration de vos plateformes Exchange.

Merci au passage à Thomas ANDRES et Yohan BOULLIER pour leur précieuse participation à l’élaboration de ce script !

Ce script va vous permettre de placer des permissions de délégations sur les boîtes à distance, à l’aide d’un compte ayant ces droits spécifiques pour placer des droits dans les Boîtes Exchange de vos utilisateurs

Pour plus de renseignements sur les droits nécessaires, veuillez-vous rendre sur cette page http://msdn.microsoft.com/en-us/library/bb204095(v=exchg.140).aspx

New-ManagementRoleAssignment -Name:ExchangeImpersonation -Role:ApplicationImpersonation -User:ServiceAccount


Pour vous servir de ce script, vous pouvez au choix:

  • Utiliser les paramètres powershell en entrée
  • Utiliser un fichier CSV en entrée

Les différents paramètres du script sont les suivants

  • MbxtoDelegate : Boîte à déléguer (paramètre obligatoire)
  • DelegatetoAdd : Délégué à ajouter (paramètre obligatoire)
  • InboxAccessPermissions : Droits sur la boîte de réception

Choix disponible : None, Owner, PublishingEditor, Editor, PublishingAuthor, Author, NoneditingAuthor, Reviewer, Contributor, Custom

  • CalendarAccessPermissions : Droits sur le calendrier
    • Choix disponible : None, Owner, PublishingEditor, Editor, PublishingAuthor, Author, NoneditingAuthor, Reviewer, Contributor, Custom
  • ContactAccessPermissions : Droits sur les contacts
    • Choix disponible : None, Owner, PublishingEditor, Editor, PublishingAuthor, Author, NoneditingAuthor, Reviewer, Contributor, Custom
  • GrantSendAs : Droit « Envoyer en tant que »
    • Choix disponible : $True / $False

Exemple d’utilisation sans le fichier CSV en entrée

Commande powershell

.\AddDelegates.ps1 -MbxtoDelegate DPEKMEZEXT -DelegatetoAdd TANDRESEXT -InboxAccessPermissions Editor -CalendarAccessPermissions Editor -ContactAccessPermissions Editor -GrantSendAs $False



Exemple d’utilisation avec le fichier CSV en entrée

Format du fichier CSV

MbxtoDelegate,DelegatetoAdd,InboxAccessPermissions,CalendarAccessPermissions,ContactAccessPermissions,GrantSendAs

TANDRESEXT,DPEKMEZEXT,Editor,Editor,Editor,False


Commande powershell

.\AddDelegates.ps1 -csv .\AddDelegates.csv


Resultat


#=================================================================================
#	AddDelegates.ps1
#
#	THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
#	KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
#	IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
#	PARTICULAR PURPOSE.
#
#	Description:
#
#	# Script Written By: David Pekmez ( https://unifiedit.wordpress.com )
#
#	Version: 1
#	Last Updated: 19/08/2011
#=================================================================================
#=================================================================================
# Parameter definition
#=================================================================================

Param(
	[Parameter(Mandatory=$false, Position=0, HelpMessage="Please Enter Mailbox UserName Or SMTP Address of the mailbox you want to Delegate",ValueFromPipeline=$true)][string] $MbxtoDelegate,
	[Parameter(Mandatory=$false, Position=1, HelpMessage="Please Enter Mailbox UserName Or SMTP Address of the Delegate you want to Add",ValueFromPipeline=$true)][string] $DelegatetoAdd,
	[Parameter(Mandatory=$false, HelpMessage="Please Enter Inbox Folder permissions to add to the Delegate",ValueFromPipeline=$true)][string] $InboxAccessPermissions="None",
	[Parameter(Mandatory=$false, HelpMessage="Please Enter Calendar Folder permissions to add to the Delegate",ValueFromPipeline=$true)][string] $CalendarAccessPermissions="None",
	[Parameter(Mandatory=$false, HelpMessage="Please Enter Contact Folder permissions to add to the Delegate",ValueFromPipeline=$true)][string] $ContactAccessPermissions="None",
	[Parameter(Mandatory=$false, HelpMessage="Grant the 'SendAs permission to Delegate",ValueFromPipeline=$true)][boolean] $GrantSendAs=$false,
	[Parameter(Mandatory=$false, HelpMessage="CSV Input file",ValueFromPipeline=$true)][string]$csv="none"
)

#==========================================================================
# Function that returns true if the incoming argument is a help request
#==========================================================================
function IsHelpRequest
{
	param($argument)
	return ($argument -eq "-?" -or $argument -eq "-help");
}

#==========================================================================
# Function that returns true if the incoming argument is a help request
#==========================================================================
function Debug([string]$data)
{
$var = $null
$var = get-variable($data) -ea SilentlyContinue

	if ($var)
	{
	write-host "DEBUG: " -foregroundcolor cyan -nonewline
	write-host $var.name "  " -nonewline
	write-host "[$var.value]"
	}
	else
	{
	write-host "DEBUG: " -foregroundcolor cyan -nonewline
	write-host "[$data]"
	}

}

#==========================================================================
# Wait until Key press
#==========================================================================
function Pause ($Message="Press any key to continue...")
{
Write-Host -NoNewLine $Message
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host ""
}
#===================================================================
# Function that displays the help related to this script following
# the same format provided by get-help or <cmdletcall> -?
#===================================================================
function Usage
{

@"
NAME: AddDelegates.ps1

SYNOPSIS:
AddDelegates to a Mailbox

SYNTAX:
AddDelegates.ps1

`t[-MbxtoDelegate <Mailbox UserName Or SMTP Address>]
`t[-DelegatetoAdd <Mailbox UserName Or SMTP Address>]
`t[-InboxAccessPermissions <Inbox Access Right>]
`t[-CalendarAccessPermissions <Calendar Access Right>]
`t[-ContactAccessPermissions <Contact Access Right>]
`t[-GrantSendAs <True/False>]
`t[-CSV <CSV file path>]

PARAMETERS:
-MbxtoDelegate (Requiered)
Mailbox UserName Or SMTP Address of the mailbox you want to Delegate

-DelegatetoAdd (Requiered)
Mailbox UserName Or SMTP Address of the Delegate you want to Add

-InboxAccessPermissions (Optionnal)
Inbox Folder permissions to add to the Delegate

-CalendarAccessPermissions (Optionnal)
Calendar Folder permissions to add to the Delegate

-ContactAccessPermissions (Optionnal)
Contact Folder permissions to add to the Delegate

-GrantSendAS (Optionnal)
Determine if the delegate must have the SendAs permission on the mailbox

-csv (Optionnal)
Specify a CSV file which contains one delegate per line

	CSV header file:
	MbxtoDelegate,DelegatetoAdd,InboxAccessPermissions,CalendarAccessPermissions,ContactAccessPermissions,GrantSendAs

-------------------------- EXAMPLE --------------------------

.\AddDelegates.ps1 -MbxtoDelegate dpekmez -DelegatetoAdd JohnDoe -InboxAccessPermissions Reviewer -CalendarAccessPermissions Editor -ContactAccessPermissions
.\AddDelegates.ps1 -csv input.csv
Mailbox folder and Calendar folder permission levels available : None, Owner, PublishingEditor, Editor, PublishingAuthor, Author, NoneditingAuthor, Reviewer, Contributor, Custom

For more information of permission level, you might want to have a look on the MDSN web Site
http://msdn.microsoft.com/en-us/library/bb856574(v=exchg.140).aspx

"@
}

#=======================================
# Check for Usage Statement Request
#=======================================
$args | foreach { if (IsHelpRequest $_) { Usage; exit; } }

#=================================================================================
# Exchange WebServices
#=================================================================================
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())

#=================================================================================
# Get Current Domain
#=================================================================================

$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

#=================================================================================
# Main
#=================================================================================
function AddDelegate ([string] $MbxtoDelegate,[string] $DelegatetoAdd,[string] $InboxAccessPermissions,[string] $CalendarAccessPermissions,[string] $ContactAccessPermissions,[boolean] $GrantSendAs)
{
	#Connexion aux boites
	$Mailbox = $null;$Mailbox = get-mailbox $MbxtoDelegate -resultsize unlimited -ea stop
	$Delegate= $null;$Delegate = get-mailbox $DelegatetoAdd -resultsize unlimited -ea stop

	#initialisation des objets Web Services
	$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $Mailbox.primarySMTPAddress.tostring());
	$mbMailbox=$null ; $mbMailbox = new-object Microsoft.Exchange.WebServices.Data.Mailbox($Mailbox.primarySMTPAddress.tostring())
	$dgUser=$null ; $dgUser = new-object Microsoft.Exchange.WebServices.Data.DelegateUser($Delegate.primarySMTPAddress.tostring())
	$dgUser.ViewPrivateItems = $false
	$dgUser.ReceiveCopiesOfMeetingMessages = $false
	$dgUser.Permissions.InboxFolderPermissionLevel = [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::$InboxAccessPermissions
	$dgUser.Permissions.CalendarFolderPermissionLevel = [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::$CalendarAccessPermissions
	$dgUser.Permissions.ContactsFolderPermissionLevel = [Microsoft.Exchange.WebServices.Data.DelegateFolderPermissionLevel]::$ContactAccessPermissions
	$dgArray = new-object Microsoft.Exchange.WebServices.Data.DelegateUser[] 1
	$dgArray[0] = $dgUser
	$Delegate_list = $service.GetDelegates($mbMailbox, $true)
	write-host ""

	# Permissions

	$Permissions = (get-MailboxFolderPermission $MbxtoDelegate) | where-object {$_.User.tostring() -eq $Delegate.DisplayName}

	if($Permissions -eq $null){

	Write-host -ForegroundColor Green "Mailbox Folder Permissions not found ..."
	Write-host -ForegroundColor Green "Set permissions for: " -nonewline
	Write-host $Delegate.DisplayName -foregroundcolor  cyan
	Add-MailboxFolderPermission -Identity $MbxtoDelegate -User $DelegatetoAdd -AccessRights $InboxAccessPermissions
    }

	elseif ($Permissions.AccessRights -eq $InboxAccessPermissions )
	{
	Write-host -ForegroundColor Green "Mailbox Folder Permissions already set for: " -nonewline
	Write-host $Delegate.DisplayName -foregroundcolor  cyan
	Write-host -ForegroundColor Green "Access Permissions: " -nonewline
	Write-host $InboxAccessPermissions -foregroundcolor  cyan
	Write-host -ForegroundColor Green "Update sub folders permissions now ..."

	}

	else {

 	Write-host -ForegroundColor Green "Mailbox Folder Permissions Different from : " -nonewline
 	Write-host $InboxAccessPermissions -foregroundcolor  cyan
	Write-host -ForegroundColor Green "for User: " -nonewline
 	Write-host $Delegate.DisplayName -foregroundcolor  cyan
	Write-host -ForegroundColor Green "Updating to Permissions : " -nonewline
	Write-host $InboxAccessPermissions  -foregroundcolor  cyan
	Remove-MailboxFolderPermission -Identity $MbxtoDelegate -User $DelegatetoAdd -confirm:$False
 	Add-MailboxFolderPermission -Identity $MbxtoDelegate -User $DelegatetoAdd -AccessRights $InboxAccessPermissions
 	Write-host -ForegroundColor Green "Update sub folders permissions now ..."
}

	# Delegation

	[boolean]$IsAlreadyDelegate = $false
	ForEach($Response in $Delegate_list.DelegateUserResponses)
	{
	$userid = $response.DelegateUser.UserId
	if ($Delegate.primarySMTPAddress.tostring() -eq $userid.PrimarySMTPAddress.tostring()){$IsAlreadyDelegate = $true;break}
	}
	if (!($IsAlreadyDelegate))

	{$service.AddDelegates($mbMailbox, [Microsoft.Exchange.WebServices.Data.MeetingRequestsDeliveryScope]::DelegatesAndMe, $dgArray)
	$action = "set"
	}else{
	$service.updateDelegates($mbMailbox, [Microsoft.Exchange.WebServices.Data.MeetingRequestsDeliveryScope]::DelegatesAndMe, $dgArray)
	$action = "updated"
	}

	#Récap
	Write-Host ""
	Write-Host "Boite aux lettres  : " -nonewline
	Write-Host $Mailbox.DisplayName -foregroundcolor  cyan
	Write-Host "Utilisateur délégué: " -nonewline
	Write-Host $Delegate.DisplayName -foregroundcolor  cyan

	Write-host -ForegroundColor Green "Inbox Permissions $action to:" -NoNewLine
	Write-host -ForegroundColor Yellow " " $InboxAccessPermissions " " -NoNewLine
	Write-host -ForegroundColor Green "Calendar Permissions $action to" -NoNewLine
	Write-host -ForegroundColor Yellow " " $CalendarAccessPermissions " " -NoNewLine
	Write-host -ForegroundColor Green "Contact Permissions $action to" -NoNewLine
	Write-host -ForegroundColor Yellow " " $ContactAccessPermissions

	# 'Send-AS' Permissions

	$SendAs = $false
	$Mailbox_permissions = get-adpermission $mailbox.identity  -ea stop | where { $_.user.tostring() -eq ($domain.Name + "\" + $delegate.samaccountname.tolower())}
	foreach ($ADAcePresentationObject in $Mailbox_permissions){if ($ADAcePresentationObject.ExtendedRights -like "*Send*") {$SendAs = $true;break}}
	write-host  "Send-As permission: " -nonewline  -ForegroundColor Green

	if ($GrantSendAs -and !($SendAs)){
	write-host  " granted." -ForegroundColor Yellow
	Add-ADPermission $mailbox.identity -User $delegate.identity -Extendedrights "Send As"}

	if ($GrantSendAs -and $SendAs){write-host  " already set." -ForegroundColor Yellow}
	if (!($GrantSendAs) -and !($SendAs)){write-host  " not set." -ForegroundColor Yellow}

	if (!($GrantSendAs) -and $SendAs){
	write-host  " removed." -ForegroundColor Yellow
	remove-ADPermission $mailbox.identity -User $delegate.identity -Extendedrights "Send As" -confirm:$false}

}

#=================================================================================
#MAIN
#=================================================================================

if ($csv -eq "none"){AddDelegate $MbxtoDelegate $DelegatetoAdd $InboxAccessPermissions $CalendarAccessPermissions $ContactAccessPermissions $GrantSendAs}
else{
	$curdir =(get-location).path
	if (!(test-path $csv)){$csv=$curdir+"\"+$csv}
	if (!(test-path $csv)){write-host "Impossible de trouver le fichier CSV:" -backgroundcolor red -nonewline ;write-host "'$csv'" -foregroundcolor cyan;write-host "";exit}
	$csvdata = import-csv $csv
	$csvdata | %{
	[Boolean]$sa = $False;$sa = [System.Convert]::ToBoolean($_.GrantSendAs.tostring())
	AddDelegate $_.MbxtoDelegate $_.DelegatetoAdd $_.InboxAccessPermissions $_.CalendarAccessPermissions $_.ContactAccessPermissions $sa}
	}

#=================================================================================
#Gestion des erreurs
#=================================================================================
trap
{
write-host ""

	if ( $_.FullyQualifiedErrorID.tostring().contains("GetMailbox"))
	{
		if ($_.Exception.Message.tostring().contains("introuvable"))
		{
		write-host "Impossible de trouver la boite aux lettres:" -backgroundcolor red -nonewline
		[int]$io1 = $_.Exception.Message.tostring().indexof("'",43)
		[int]$io2 = $_.Exception.Message.tostring().indexof("'",$io1+1)
		$bal = $_.Exception.Message.tostring().substring($io1+1,$io2-$io1-1)
		write-host " " $bal -foregroundcolor cyan
		write-host ""
		exit
		}
	}

	if ($_.Exception.Message.tostring().contains("DelegateFolderPermissionLevel"))
	{
		write-host "Permission incorrecte pour le dossier:" -backgroundcolor red -nonewline
		[int]$io1= $_.Exception.Message.tostring().indexof("«")
		[int]$io2= $_.Exception.Message.tostring().indexof("»")
		$folder = $_.Exception.Message.tostring().substring($io1+1,$io2-$io1-1)
		$folder = $folder -replace("FolderPermissionLevel","")
		write-host " " $folder -foregroundcolor cyan
		write-host ""
		write-host "Permissions prises en charge:"
		write-host ""
		write-host " - None"
		write-host " - Editor"
		write-host " - Reviewer"
		write-host " - Author"
		write-host " - Custom"
		write-host ""
		exit
	}

	if ($_.Exception.Message.tostring().contains("ToBoolean"))
	{
		write-host "Valeur incorrecte dans le ficheir CSV pour la colonne :" -backgroundcolor red -nonewline
		write-host " 'GrantSendAs'" -foregroundcolor cyan
		write-host "Valeurs autorisées : 'true' ou 'false'"
		write-host ""
		exit
	}

	write-host ""
	write-host ""
	write-host "------------------------------------------------------"
	write-host "categoryInfo: " -backgroundcolor red -nonewline
	write-host $_.categoryInfo
	write-host "Exception.GetType: " -backgroundcolor red -nonewline
	write-host $_.Exception.GetType().fullname
	write-host "FullyQualifiedErrorID: " -backgroundcolor red -nonewline
	write-host $_.FullyQualifiedErrorID
	write-host "Message: " -backgroundcolor red -nonewline
	write-host $_.Exception.Message
	write-host "------------------------------------------------------"
	exit
}


Ce script est téléchargeable via le lien suivant

https://skydrive.live.com/?cid=deb7bf8a12d36694&sc=documents&id=DEB7BF8A12D36694%21410#

Voilà, j’espère que ce script vous sera utile !

Bonne lecture

David Pekmez

Laisser un commentaire

Choisissez une méthode de connexion pour poster votre commentaire:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

 
%d blogueurs aiment cette page :