$Recipient = $Mailbox = $null

## Try and find the recipient, throw an error if it doesn't exist.
$Recipient = Get-Recipient -Identity [!user-importname] -ErrorAcction Stop

switch($Recipient.RecipientType)
{
	'UserMailbox' 
	{
		## we set a variable in cloudmigrator to determine whether or not to clear
		## the forwarder before the migration.
		if('[!remove-forwarder]' -eq 'True')
		{
			Set-Mailbox `
				-Identity $Recipient.Identity `
				-DomainController $Recipient.OriginatingServer `
				-ForwardingSMTPAddress:$NULL `
				-ErrorAction Stop
		}
		else
		{
			## Mailbox already exists, so we do nothing and just carry on with data migration.
			return $true
		}
	}
	'MailUser'
	{
		if('[!remove-forwarder]' -eq 'True')
		{
			## we shouldn't see migrate-
			## then throw an error as that's unexpected.
			throw "Unexpected recipient type: $($Recipient.RecipientType) and remove-forwarder was set to true."
		}
		
		## Object is a mail user, enable the mailbox and set the forwarder.
		Enable-Mailbox `
			-Identity $Recipient.Identity `
			-DomainController $Recipient.OriginatingServer `
			-ErrorAction Stop
			
		Set-Mailbox `
			-ErrorAction Stop `
			-Identity $Recipient.Identity `
			-DomainController $Recipient.OriginatingServer `
			-ForwardingSMTPAddress '[!user-importname]@notes.ons.gov.uk'			
		## The importname is the alias on exchange and in some rare cases may not match notes.

		## Have a nap so the EWS connection doesn't fail.
		Start-Sleep -Seconds 15
	}
	default 
	{
		## If it's not a MailUser or a Mailbox, bomb out and deal with it manually.
		throw "Unexpected recipient type: $($Recipient.RecipientType)"
	}
}