Race conditions in account creation script with email account and Office 365 sync--any good way besides time delay to resolve?
I have a powershell script that I use to create new users. Every year we add hundreds of interns, so automation is crucial. Someone in HR runs the script, so the script is supposed to be foolproof.
I am running into a race condition with two new features I have added, and I would like to resolve it in a more reliable way than the current method (sleep 2 minutes), which still fails intermittently.
1) Office 365 license activation. I force a sync of Office 365 with our local AD by using the Start-OnlineCoexistenceSync
command prior to attempting the license activation. As far as I can tell, there is no way to check the status of the sync. So I delay 2 minutes. In tests this has worked, but in production it works intermittently. I assume expanding the wait would resolve, but 2 minutes already feels long. And clearly sometimes it is longer than needed, I hate to have an unnecessary delay.
2) Sending a welcome email message. Accounts can take a variable amount of time to create (and sometimes fail altogether), but I don't want to unduly delay the script.
Any suggestions on how to resolve?
The Start-OnlineCoexistenceSync
cmdlet should produce an event in the event log (of the directory server) with event ID 4 and event source "Directory Synchronization" and say something like "The export has completed" that will indicate that the directory synchronization is complete.
So what you want to do is make your Powershell script wait for that event to pop up. That way you are only waiting as long as you need to and no longer. Of course you'll want to also code in error conditions like a maximum amount of time you will wait for that event until you give up, etc.