# M365 - Scripts

# Distribution Lists

# Powershell to Bulk Add Users to Different Distribution lists

```powershell
$CSVFile = "C:\Temp\DL-Group-Members.csv"

Try {
    #Connect to Exchange Online
    Connect-ExchangeOnline -ShowBanner:$False

    #Get date from CSV File
    $CSVData = Import-Csv -Path $CSVFile

    #Iterate through each row in the CSV
    ForEach($Row in $CSVData)
    {
        #Get the Distribution Group
        $Group = Get-DistributionGroup -Identity $Row.GroupEmail

        If($Null -ne $Group)
        {
            #Get Exisiting Members of the Group
            $GroupMembers = Get-DistributionGroupMember -Identity $Row.GroupEmail -ResultSize Unlimited | Select-Object -Expand PrimarySmtpAddress

            #Get Users to Add to the Group
            $UsersToAdd =  $Row.Users -split ","

            #Add Each user to the Security group
            ForEach ($User in $UsersToAdd)
            {
                #Check if the group has the member already
                If($GroupMembers -contains $User)
                {
                    Write-host "'$($User)' is already a Member of the Group '$($Group.DisplayName)'" -f Yellow
                }
                Else
                {
                    Add-DistributionGroupMember –Identity $Row.GroupEmail -Member $User
                    Write-host -f Green "Added Member '$User' to the Group '$($Group.DisplayName)'"
                }
            }
        }
        Else
        {
            Write-host "Could not Find Group:"$Row.GroupName
        }
    }
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}
```

Prepare a CSV file containing the email addresses of the users you want to add to the distribution list. The CSV file should have a header row with the following column names: GroupEmail, and Users. Here is my CSV template:

[Original Article](https://www.sharepointdiary.com/2021/03/add-members-to-distribution-list-in-office-365-powershell.html#:~:text=Click%20on%20the%20%E2%80%9CMembers%E2%80%9D%20tab,add%20to%20the%20distribution%20list.)

# PowerShell to Import Distribution List Members From CSV/TXT

```powershell
$GroupEmailID = "Sales@Crescent.com"
$CSVFile = "C:\Temp\DL-Members.txt"

#Connect to Exchange Online
Connect-ExchangeOnline -ShowBanner:$False

#Get Existing Members of the Distribution List
$DLMembers =  Get-DistributionGroupMember -Identity $GroupEmailID -ResultSize Unlimited | Select-Object -Expand PrimarySmtpAddress

#Import Distribution List Members from CSV
Import-CSV $CSVFile -Header "UPN" | ForEach-Object {
    #Check if the Distribution List contains the particular user
    If ($DLMembers -contains $_.UPN)
    {
        Write-host -f Yellow "User is already member of the Distribution List:"$_.UPN
    }
    Else
    {
        Add-DistributionGroupMember –Identity $GroupEmailID -Member $_.UPN
        Write-host -f Green "Added User to Distribution List:"$_.UPN
    }
}
```

# Powershell to List Users That Are NOT Members of Listed Distribution Lists

```powershell
# Define the list of distribution lists
$distributionLists = @("Managers", "Senior Managers")

# Function to get members of a distribution list
function Get-DistributionListMembers {
    param (
        [string]$distributionListName
    )

    $members = Get-DistributionGroupMember -Identity $distributionListName | Select-Object -ExpandProperty PrimarySmtpAddress
    return $members
}

# Function to get all users
function Get-AllUsers {
    $users = Get-ADUser -Properties * -Filter *
    return $users
}

# Create an array to store all users
$allUsers = Get-AllUsers

# Create an array to store members of all distribution lists
$allListMembers = @()

# Populate $allListMembers with members of each distribution list
foreach ($list in $distributionLists) {
    $listMembers = Get-DistributionListMembers -distributionListName $list
    $allListMembers += $listMembers
}

# Find users not in any distribution list
$missingUsers = $allUsers | Where-Object { $_.UserPrincipalName -notin $allListMembers }

# Export results to CSV
$missingUsers | Select-Object UserPrincipalName, Name, Enabled, Title, Department, DistinguishedName, LastLogonDate | Export-Csv -Path "C:\temp\Distlist.csv" -NoTypeInformation

```

# Email Management

# Delete Email From All Mailboxes In Office 365

<p class="callout info">For full details please go to the following page [Delete Email From All Mailboxes In Office 365](https://wikipedia.mutschlerhome.com/attachments/33)</p>

<p class="callout success">This assumes the following are true  
**Subject: You must change your bank password now**  
**Sent: 05/12/2020**</p>

### 1. Connect to MSOnline in Powershell

```none
Import-Module ExchangeOnlineManagement
Connect-IPPSSession -UserPrincipalName "UPN"
```

### 2. Create a New Compliance Search in Powershell, preferably Powershell ISE

```
New-ComplianceSearch `
-Name Phish1 `
-ExchangeLocation All `
-ContentMatchQuery 'subject:"You must change your bank password now" AND sent:05/12/2020'
```

### 3. Start the Compliance Search

```
Start-ComplianceSearch -Identity Phish1
```

### 4. Check the Status of/Verify the Search Completes

```
Get-ComplianceSearch -Identity Phish1
```

### 5. Verify Items Found Match the Number of Emails Expected

```
Get-ComplianceSearch -Identity Phish1 | Format-List *
```

### 6. Create Preview of the Search Results

```
New-ComplianceSearchAction -SearchName Phish1 -Preview
```

### 7. Preview the Search Results

```
(Get-ComplianceSearchAction Phish1_Preview | Select-Object -ExpandProperty Results) -split ","
```

### (Optional) Download Results From [Security and Compliance Center Portal](https://docs.microsoft.com/en-us/microsoft-365/compliance/export-a-content-search-report?view=o365-worldwide#step-2-download-the-report)

### 8. Delete Email From All Mailboxes In Office 365 With Soft Delete

```
New-ComplianceSearchAction -SearchName Phish1 -Purge -PurgeType SoftDelete
```

### 9. View Result of Purge

```
Get-ComplianceSearchAction -Identity Phish1_Purge | Format-List
```