top of page
  • ExchangeMaster

Invoke AADC ("DirSync") from PowerShell

Updated: Apr 20, 2021

Another quick-hit script along with a few ancillary thoughts on invoking O365 Azure AD Sync (or "DirSync") from PowerShell. I invoke a sync on the active Azure AD Connect server (of course), usually from a "staged' AADC server as it already has the ADSync.psd1 file mentioned below. You can use this code anytime you need to verify that a sync has run and completed before your larger script continues, or even standalone as a better way to manually run a sync.



Import-Module ADSync

$AADCSession = New-PSSession -ComputerName "ActiveDirSyncBox.contoso.com" -Authentication Kerberos -Credential $credential

Invoke-Command -Session $AADCSession -ScriptBlock {Import-Module "C:\Program Files\Microsoft Azure AD Sync\Bin\ADSync\ADSync.psd1"}

while (!(Invoke-Command -Session $AADCSession -ScriptBlock {Start-ADSyncSyncCycle -PolicyType Delta})){Start-Sleep -Seconds 30}
$Tstamp = Get-Date

# Set sleep here to allow time for sync, once invoked.
Start-Sleep -Seconds 300

while (!(Get-EventLog -LogName Application -after $Tstamp -InstanceId 904 -Newest 25 -Message "Scheduler::SchedulerThreadMain : Completed configured scheduler operations." -ComputerName ActiveDirSyncBox.contoso.com)) {Start-Sleep -Seconds 30} 

#Optional entry in the Application log; comment if not needed.
Write-EventLog -LogName Application -ComputerName ActiveDirSyncBox.contoso.com -Source "Directory Synchronization" -EventId 30000 -Message "This event signals the end of a scripted AADC cycle."

# Cleanup the session.
Remove-PSSession $AADCSession

A few final thoughts: first, just by changing the -ComputerName values above, you can easily make this a local operation for a script running on your AADC box. And for storing creds for the "$Credential" variable, I recommend Aaron Guilmette's method.


An interactive "manual sync" version of this can be handy as well; you could add "$start" and "$end" variables using Get-Date, and Write-Host your start and end times for on-screen confirmation of a complete cycle.


Finally, if you notice over time that your script begins to take longer to finish, and you suspect that the invoked DirSync is the cause, check that the Application log on the active AADC server hasn't grown too large. If the Application log's size is the default (20480 KB, I think), you should not encounter this problem. A larger log can take far longer to read.

85 views0 comments

Recent Posts

See All

To avoid unpredictable results due to your script reading from or writing to "random" domain controllers, it's good practice to use the -Server or -DomainController parameter pertinent to a given cmdl

Recently I needed a quick script to set the two-letter O365 country codes, while my only source for the setting was the three-letter codes in a given AD forest. This presented a problem, because O365

bottom of page