reset counter


with the code below I’m checking the difference between the last Sync Time between on premises AD management server and AzureAD.
this is working just fine as long as you don’t execute the script somewhere between the 27th and 30 min after the last sync then it will result in an error and you have to wait till the next cycle in order to continue

what would be the easiest way to reset the counter or relaunch this script when started in the above mentioned time frame after last sync


$username = $env:USERNAME
$cred = Import-Clixml -Path “c:\temp\cred$username.Cred”
#Connect-MsolService -Credential $cred
$GracePeriodMin = 31

[DateTime]$LastDirSyncTime = (Get-MsolCompanyInformation).LastDirSyncTime # Assuming this time is UTC

Using .ToUniversalTime() method of the DateTime object to obtain current UTC time

$MinutesSinceLastSync = [Math]::Round((New-TimeSpan -Start $LastDirSyncTime -End (Get-Date).ToUniversalTime()).TotalMinutes,0)
Write-Output “Last Dir Sync Time was ‘$LastDirSyncTime’ UTC - that’s ‘$MinutesSinceLastSync’ minutes ago”
Write-host -ForegroundColor cyan “you can now modify the globalDDI.xlsx sheet”
$counter = $GracePeriodMin - $MinutesSinceLastSync
$Zcounter = $counter++

while ($zcounter -ne 0) {
#Write-host -ForegroundColor yellow “$zcounter: '$zcounter'" -NoNewline #Write-host -ForegroundColor Green "$counter: ‘$counter’”
Write-host -ForegroundColor yellow “please return in ‘$Zcounter’ min for the second part of the offboarding script”

Start-Sleep -seconds 60

#if($zcounter -eq “-1”){break}
write-host -ForegroundColor Magenta “Coffee Break is over get moving… :)”


thanks for your Idea’s


I’d recommend analyzing and correcting the error instead of working around. :wink:

Hello Paul,

I agree with Olaf workarounding error is not the solution.

Would you be so kind to provide more details from the business side? I am assuming this is part of the onboarding process. Why you need to wait? What is happening during the wait, another script?

With more details it will be easier to suggest some ideas and improvements.


Thank you.


thanks Andy for your reaction,

the waiting period is nothing more then waiting till the sync is done between on premises AD and AzureAD because I can only continue when the account of this given user is disabled.

I think that from time to time the Sync is slower then the script itself which will result in the fact that the account is not updated in AzureAD in time.

hope this helps