Powershell create distribution lists

When you have imbricated group (distribution lists, dynamics lists, …) and you need to build a flat distribution list with unique mailbox, here is a script which create distribution list based on the prefix of dynamic list in input $company$_Distribution_Collaborateurs

<#	
	.NOTES
	===========================================================================
	 Created with: 	SAPIEN Technologies, Inc., PowerShell Studio 2021 v5.8.191
	 Created on:   	26/12/2024 12:02
	 Created by:   	Jean-Yves Moschetto - jeanyves.moschetto@anvole.com
	 Organization: 	ANVOLE
	 Filename:     	Exchange-Create-DistributionLists-From-Companies
	===========================================================================
	.DESCRIPTION
		A description of the file.
#>

# A exécuter une seule fois
Install-Module ExchangeOnlineManagement -Force

#Do JOB
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline

#Fonction récursive pour descendre dans les listes incluant d'autres listes, statiques ou dynamiques'
function myGetMember
{
	param($ObjId, $ObjType, $Level)
	$Level+=1
	Write-Host (("   ") * $Level)"Get-Members: " $ObjId " " $objType
	switch ($ObjType)
	{
		"DynamicDistributionGroup" { foreach ($obj in Get-DynamicDistributionGroupMember $ObjId) { myGetMember -ObjId $obj.Name -ObjType $obj.RecipientTypeDetails -Level $Level	} }
		"MailUniversalDistributionGroup" { foreach ($obj in Get-DistributionGroupMember $ObjId) { myGetMember -ObjId $obj.Name -ObjType $obj.RecipientTypeDetails -Level $Level} }
		"UserMailbox" { $Global:UserMembers += $objId }
		"SharedMailbox" {}
		"User" { }
		"DisabledUser" {}
	}
}

$Lists = Get-DistributionGroup "*_Distribution_Collaborateurs" | Sort-Object 'DisplayName' 
foreach ($List in $Lists)
{
	"`r`nLIST : " + $List.DisplayName
	#Create ARSEN group from DistributionListName
	$Pos = $($List.DisplayName).IndexOf('_Distribution_Collaborateurs')
	$ARSEN = 'ARSEN_' + $($List.DisplayName).Substring(0, $Pos)
	"ARSEN : " + $ARSEN
	Start-Sleep -Seconds 2
	
	$Global:UserMembers = @()
	#Exécute en récursif la fonction
	myGetMember -ObjId $List.Identity -ObjType $List.RecipientTypeDetails -Level 0
	
	
	#Crée la liste si elle n'existe pas
	if ((Get-DistributionGroup $ARSEN -ErrorAction SilentlyContinue) -eq $null)
	{
		New-DistributionGroup -Name $ARSEN | Out-Null
		Set-DistributionGroup $ARSEN -HiddenFromAddressListsEnabled $true
	}
	Write-Host "Mise à jour de la liste des membres de:" $ARSEN
	Update-DistributionGroupMember -Identity $ARSEN -Confirm:$false -Members $($Global:UserMembers | Sort-Object -Unique)
}
Retour en haut