Use PowerShell to clone DL's from one user to another in O365

At my workplace we are using lots of distribution lists in O365 to move information around. Because of this, in some departments, the employees can be part of many DL's. During onboarding this is annoying as it's not very easy to track those.

Lucky me that O365 has a very good PowerShell integration. In this article I will teach you how to:

  1. Prepare your powershell to run scripts
  2. Connect to O365 Exchange Online via PowerShell
  3. Copy DL membership from an existing user to another
  4. Disconnect from O365 Exchange Online

1. PowerShell Execution Policy

The PowerShell Execution Policy is part of the PowerShell security. It dictates whether you can load config files, run scripts or if those scripts must be digitally signed before you can run them.

I will not get into explaining the execution policies or the scope of them here. If you want to learn more about that you can do it here.

What we need to do here is to set our execution policy as RemoteSigned. This will allow us to run scripts.

To set this policy you need to open a PowerShell as an administrator

Screenshot 2020-09-11 at 20.25.28.png

and run the following command

Set-ExecutionPolicy RemoteSigned -force

You can now check that the policy used for your LocalMachine scope is RemoteSigned by running:

Get-ExecutionPolicy -List

Screenshot 2020-09-11 at 20.26.09.png

You will now be able to connect to O365 with Powershell.

2. Connect to O365 Echange Online via PowerShell

The process to connect from PowerShell to O365 Echange Online is pretty straightforward.

  1. Open PoweShell
  2. Store your credentials in a variable:

    $Cred = Get-Credential
  3. Enter your username and password in the prompt.

  4. Type the following command:
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $Cred -Authentication Basic –AllowRedirection
  5. Import your session:

    Import-PSSession $Session
  6. Now you can run any commands you need.

3. Copy DL membership from an existing user to another

Adjust the following code snippet and run it:

$dists= Get-DistributionGroup
$sourceMailbox = Get-Mailbox ''

foreach($dist in $dists){
    $gms = Get-DistributionGroupMember -identity $dist.Identity
    foreach ($gm in $gms){
       if ($ -eq ${
          write-host 'User Found In Group'   $dist.Alias
          Add-DistributionGroupMember -Identity $dist.Alias -Member ""

This snippet will do the following:

  • iterate through all distribution groups in your organisation
  • on each iteration it will check if $sourceMailbox is part of that list
  • if it is, it will also add the new mailbox to that list

4. Disconnect from O365 Exchange Online

Disconnecting from your session is as simple as typing:

Remove-PSSession $Session

You can access the complete script on GitHub.

If you liked my article and want to hear more from me you can find me on Twitter!

Share this