O365: My “Shared Mailbox Maintenance” Script

I have been doing a lot of work recently for a client on Office 365, and as part of my role, I have to provide some first line support when required.  Some of the tasks are really basic but very repetitive – like adding user access to Shared Mailboxes.  After a while I was getting tired of searching for the same set of commands, so I decided it would save me some time if I put all my most commonly used commands for Shared Mailboxes into one big PowerShell script!

As always, make sure you do your own testing if you want to use this script to make sure that it works as intended!

<#
.SYNOPSIS
    Script designed to make giving access to various parts of a shared mailbox in Office 365 easier
.DESCRIPTION
    Script designed to make giving access to various parts of a shared mailbox in Office 365 easier

.NOTES
    Author: Robert Milner
    Version: 1.1
    Date Released: 27/04/2018
    PowerShell Versions Tested: v5
    O/S Versions Tested: Windows 10

.EXAMPLE
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -UserAccess "FirstN LastN" -SetFullAccess
This command will give someone full access to a shared mailbox, with automap disabled

.EXAMPLE
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -UserAccess "FirstN LastN" -SetFullAccess -SetSendAs
This command will give someone full access to a shared mailbox, with automap disabled and Send As permissions

.EXAMPLE
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -UserAccess "FirstN LastN" -SetFullAccess -SetSendAs -SetSendOnBehalf
This command will give someone full access to a shared mailbox, with automap disabled, Send As and Send On Behalf permissions

.EXAMPLE
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -SetSaveSent
This command will save a copy of sent E-Mails into the shared mailbox

.EXAMPLE
There are various get commands as well which can be run against a mailbox to see what is set

To see Send As Permissions:
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -GetSendAs

To see Send On Behalf Permissions:
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -GetSendOnBehalf

To see if save a copy of sent items in mailbox is enabled:
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -GetSaveSent

.EXAMPLE
&.\'O365 - Mailbox Maintenance.ps1' -Mailbox "[email protected]" -CopySendAsToSendOnBehalf
This command will copy the Send As permissions to the Send On Behalf permissions

#>

<#
CHANGE LOG:
1.1 Initial Script Creation
#>

[CmdletBinding()]
param (
	
	[Parameter( Mandatory=$false )]
	[string]$UserAccess,

    [Parameter( Mandatory=$true )]
    [string]$Mailbox,

    [Parameter( Mandatory=$false )]
    [switch]$RemoveExistingAccess,

    [Parameter( Mandatory=$false )]
    [switch]$SetSendAs,

    [Parameter( Mandatory=$false )]
    [switch]$GetSendAs,

    [Parameter( Mandatory=$false )]
    [switch]$SetSendOnBehalf,

    [Parameter( Mandatory=$false )]
    [switch]$GetSendOnBehalf,

    [Parameter( Mandatory=$false )]
    [switch]$GetSaveSent,

    [Parameter( Mandatory=$false )]
    [switch]$SetSaveSent,

    [Parameter( Mandatory=$false )]
    [switch]$SetFullAccess,

    [Parameter( Mandatory=$false )]
    [switch]$CopySendAsToSendOnBehalf

    )

#...................................
# Variables
#...................................

$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path

$logfile = "$myDir\Add Mailbox Permission Automap Disabled.log"

#...................................
# Functions
#...................................

#This function is used to write the log file
function WriteTo-Log
{
    param (
        [string]$String="*",
        [string]$Logfile = $Logfile,
        [Switch]$OutputToScreen,
        [ValidateSet("Black","DarkBlue","DarkGreen","DarkCyan","DarkRed","DarkMagenta","DarkYellow","Gray","DarkGray","Blue","Green","Cyan","Red","Magenta","Yellow","White")]
        [String]$ForegroundColor=(Get-Host).ui.RawUI.ForegroundColor,
        [ValidateSet("Black","DarkBlue","DarkGreen","DarkCyan","DarkRed","DarkMagenta","DarkYellow","Gray","DarkGray","Blue","Green","Cyan","Red","Magenta","Yellow","White")]
        [String]$BackgroundColor=(Get-Host).ui.RawUI.BackgroundColor
        )
    
    if ($LogFile -eq "") {
        $LogFile = ('.\'+(Get-History -Id ($MyInvocation.HistoryId -1) | Select-Object StartExecutionTime).startexecutiontime.tostring('yyyyMMdd-HHmm')+'-'+[io.path]::GetFileNameWithoutExtension($MyInvocation.ScriptName)+'.log')
    }

    if (!(Test-Path $LogFile)) {
        Write-Output "Creating log file $LogFile"
        $LogFile = New-Item $LogFile -Type file
    }

	$datetime = (Get-Date).ToString('yyyyMMdd HH:mm:ss')
    $StringToWrite = "$datetime | $String"
	if ($OutputToScreen) {Write-Host $StringToWrite -ForegroundColor $ForegroundColor -BackgroundColor $BackgroundColor}
    Add-Content -Path $LogFile -Value $StringToWrite
}

#...................................
# Script
#...................................

try
{
    # Remove access if specified
    if ($RemoveExistingAccess)
    {
        if (!($UserAccess))
        {
            WriteTo-Log "No User Specified - Please Use The -UserAccess Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        elseif (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Removing Mailbox Permission" -OutputToScreen
        Remove-MailboxPermission -Identity $Mailbox -User $UserAccess -AccessRights FullAccess
        Remove-MailboxPermission -Identity $Mailbox -User $UserAccess -AccessRights SendAs
    }

    # Add Send As Permissions
    if ($SetSendAs)
    {
        if (!($UserAccess))
        {
            WriteTo-Log "No User Specified - Please Use The -UserAccess Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        elseif (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Adding Send As Permission" -OutputToScreen
        Add-RecipientPermission -Identity $Mailbox -AccessRights SendAs -Trustee $UserAccess -Confirm:$False
        Write-Host ""
        WriteTo-Log "New Send As Permissions:" -OutputToScreen
        Get-RecipientPermission -Identity $Mailbox -AccessRights SendAs | Format-Table Trustee
    }

    # Get Send As Permissions
    if ($GetSendAs)
    {
        if (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Current Send As Permissions:" -OutputToScreen
        Get-RecipientPermission -Identity $Mailbox -AccessRights SendAs | Format-Table Trustee
    }

    # Add Send On Behalf Permissions
    if ($SetSendOnBehalf)
    {
        if (!($UserAccess))
        {
            WriteTo-Log "No User Specified - Please Use The -UserAccess Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        elseif (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Adding Send On Behalf Permission" -OutputToScreen
        Set-Mailbox -Identity $Mailbox -GrantSendOnBehalfTo @{add="$UserAccess"}
        Write-Host ""
        WriteTo-Log "New Send On Behalf Permissions:" -OutputToScreen
        Get-Mailbox -Identity $Mailbox | Select-Object -ExpandProperty grantsendonbehalfto
    }

    # Get Send On Behalf Permissions
    if ($GetSendOnBehalf)
    {
        if (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Current Send On Behalf Permissions:" -OutputToScreen
        Write-Host ""
        Get-Mailbox -Identity $Mailbox | Select-Object -ExpandProperty grantsendonbehalfto
    }

    # Get Save Sent Items Configuration
    if ($GetSaveSent)
    {
        if (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Current Message Copy Settings:" -OutputToScreen
        Get-Mailbox -Identity $Mailbox | Format-Table Alias,MessageCopy*
    }

    # Set Save Items In Mailbox
    if ($SetSaveSent)
    {
        if (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Setting Message Copy Settings" -OutputToScreen
        Set-Mailbox -Identity $Mailbox -MessageCopyForSendOnBehalfEnabled $True
        Set-Mailbox -Identity $Mailbox -MessageCopyForSentAsEnabled $True
        Get-Mailbox -Identity $Mailbox | Format-Table Alias,MessageCopy*
    }

    # Set Full Access Permissions
    if ($SetFullAccess)
    {
        if (!($UserAccess))
        {
            WriteTo-Log "No User Specified - Please Use The -UserAccess Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        elseif (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        WriteTo-Log "Adding Mailbox Permission For $UserAccess To $Mailbox" -OutputToScreen
        Add-MailboxPermission -Identity $Mailbox -User $UserAccess -AccessRights FullAccess -Inheritance All -AutoMapping $false
        WriteTo-Log "DONE" -OutputToScreen
    }

    # Copy Send As to Send On Behalf
    if ($CopySendAsToSendOnBehalf)
    {
        if (!($Mailbox))
        {
            WriteTo-Log "No Mailbox Specified - Please Use The -Mailbox Parameter" -OutputToScreen -ForegroundColor Red
            break
        }
        $CSVFile = ('.\sendasmembers.csv')
        WriteTo-Log "Copying members from Send As to Send On Behalf" -OutputToScreen
        Get-RecipientPermission -Identity $Mailbox -AccessRights SendAs | Select-Object Trustee | Export-Csv $CSVFile
        Start-Sleep -Seconds 5

        $csv = Import-Csv $CSVFile

        foreach ($member in $csv)
        {
            $permission = $member.trustee
            Set-Mailbox -Identity $Mailbox -GrantSendOnBehalfTo @{add="$permission"}
        }

        Remove-Item -Path $CSVFile -Force
    }
}
catch
{
    WriteTo-Log $_.exception.message -OutputToScreen
}