Powershell: Run a command at specific time

  • Thread starter Grayfox
  • 6 comments
  • 7,689 views
11,678
Australia
Australia
I_Grayson_Fox_I
I have a small script for a work computer and I would like to add a command that is run at a specific time.
Since this is a work computer, I cant use Task Scheduler due to permissions.

Found this script that can restart the computer at 8PM.

[datetime]$RestartTime = '8PM'
[datetime]$CurrentTime = Get-Date
[int]$WaitSeconds = ( $RestartTime - $CurrentTime ).TotalSeconds
shutdown -r -t $WaitSeconds

Anyone to tweak this script to run any command?
 
If you're looking to start a script and have it wait for the desired time to act, then you could use a combination of Get-Date and Start-Sleep. Then it would just run whatever commands you want. In the script you quote, the Shutdown command has a wait parameter built in, but you could replicate that with Start-Sleep

[datetime]$RestartTime = '8PM'
[datetime]$CurrentTime = Get-Date
[int]$WaitSeconds = ( $RestartTime - $CurrentTime ).TotalSeconds
Start-Sleep -Seconds $WaitSeconds
<Commands to Run>
 
That's that works great, anyway to prevent the command from running after the set time?
So if I restart the script it wont run till the next time as currently it is giving me an error about the time being below 0.
 
[datetime]$RestartTime = '3AM'
$AddDaysWhenNegative = 1
[datetime]$CurrentTime = Get-Date
[int]$WaitSeconds = ( $RestartTime - $CurrentTime ).TotalSeconds
If ($WaitSeconds -lt 0) { $WaitSeconds += (New-TimeSpan -Days $AddDaysWhenNegative).TotalSeconds }
Start-Sleep -Seconds $WaitSeconds

# OR (I used it with remote shutdown here)

$ServerName = "REMOTESERVER"
[datetime]$RestartTime = '03:00' #Use '8/24/2021 03:00' for a date in the future
$AddDaysWhenInPast = 1
[datetime]$CurrentTime = Get-Date
If ($RestartTime -lt $CurrentTime) { $RestartTime = $RestartTime.AddDays($AddDaysWhenInPast) }
[int]$WaitSeconds = ( $RestartTime - $CurrentTime ).TotalSeconds
shutdown -m \\$ServerName -r -t $WaitSeconds -f -c "Scheduled Reboot script"
 
Last edited:
Totally forgot about this script thread.

Been trying to get several scripts to run co-currently

I want to add the shutdown to this

But if I was to add it after the script below, the shutdown wont work
If I add it before, the script below wont run.

Code:
$WShell = New-Object -com "Wscript.Shell"
While ($true)
{
  $WShell.sendkeys("{CAPSLOCK}")
  Start-Sleep -Milliseconds $ToggleTime
  Write-host "Press"
  $WShell.sendkeys("{CAPSLOCK}")
  Start-Sleep -Seconds $LoopTime
}

The script above prevents a work computer from going to the lock screen.
Head office wants the computer to go to sleep for secrurity reasons but since this computer will not be used for several minutes even if were in front of it, it locks out, so getting back to work can take minutes due to the user profile being online.
 
Last edited:
Back