One of the biggest challenges I faced while automating mailbox creation and migration within a hybrid Exchange/O365 environment was figuring out when Dirsync had finished running.
By default, Dirsync runs x hours after the time the last cycle completes, which means that Dirsync never really runs on a fixed schedule. But, how does Dirsync know when the cycle completed?
Turns out, there’s a value in Get-MsolCompanyInformation called LastDirsyncTime. Get that value, store it in a variable, run Dirsync, then use a while loop to compare the value in your variable with the current value of LastDirSyncTime until the current value exceeds your variable value.
Here’s the code snippet, and the full function I use for O365 to On-Prem migration is below the cut.
$DirSyncTimeBefore = Get-MsolCompanyInformation | select LastDirSyncTime
$dstimeb = $DirSyncTimeBefore.LastDirSyncTime
Write-Output "Time before is $dstimeb"
Function Invoke-MailboxMigration
{
<#
.SYNOPSIS
Migrates a mailbox from O365 to On-prem.
.DESCRIPTION
Cmdlet prepares mailbox for migration, starts dirsync, then finishes migration after dirsync has finished.
.EXAMPLE
Invoke-MailboxMigration -Username meowth -GUID "0x000x00-y0yy-000y-0000-00000z0z00zz"
#>
[CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact='Low')]
param
(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=0,HelpMessage='Please enter a username')] [string]$Username,
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=1,HelpMessage='Enter a GUID')]
[string]$GUID, [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=2,HelpMessage='Enter a database')]
[string]$Database
)
#region setup
$EmailAddress = [string]::Concat($($Username),"@domain.mail.onmicrosoft.com")
Enable-Remotemailbox $Username -remoteroutingaddress $EmailAddress
Set-Remotemailbox $Username -ExchangeGUID $GUID
Write-Output "Began migration process for $Username with remote routing address $EmailAddress and GUID $GUID"
#endregion