run script after x time

I’ve this piece of code and I wonder what’s the best way using a do while or a do until

also I want to see an update every 60 sec once the 30 min have passed I want to execute my script


$ADSync = (Get-MsolCompanyInformation).lastdirsynctime
$sync = “00:30:00”

$h = (Get-Date).AddHours(-2)
$diff = New-TimeSpan -Start $ADSync -End $h
Write-Output “time difference is $diff”
DO {sleep -s 60}
($diff -gt $sync)



# Check every 60 sec after 30 min from LastSyncTime 

$GracePeriodMin = 30 

# Install-Module msonline

while ($true) {
    [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"
    if ($MinutesSinceLastSync -ge $GracePeriodMin) {
        .\checks.ps1 # invokes Dir Sync update!?
    Start-Sleep -Seconds 60

What this will do is:

  • If the last dir sync was over 30 min ago, invokes checks.ps1
  • Runs indefinitely, checks last sync every 60 sec

Hi Sam,

thanks for your help,

I have several scripts to perform the offboarding process
1 that runs directly on AD on Premises, does the actual disabling account along with several other things
2. moving over to AZure Ad and remove all the groups a user is member of. this can only be done when the 30 min have passed
at this very moment it says last time synced is 4 min ago.
this means that the script under point 2 needs to wait at least 26 min before I can execute that script once executed this piece of code needs to stop checking till the next time it’s being used

what do I need to do in order to get it working like this?



Start-sleep -Seconds 1560 ??

Hi Doug,

fair enough but would like to have this automated then how do I do this?

uhm, nothing. Sit tight for 26 more minutes, lol

but if you must: CTRL-C

acer460527, the purpose of this forum is to help people understand PowerShell. You’re expected to demonstrate that you understand the code posted. If not, you’re expected to ask about any portion of the code that you don’t understand.


thanks for your Reaction I understand that your code runs non stop unless I hit stop code or ctrl c as you say.
I’m still learning and each time struggling with do while or do until or do and while alone

I’ll be happy to learn