2017-09-04

The Laziest Cron Job on Windows

"You know that story about how NASA spent millions of dollars developing this pen that writes in zero G? Did you ever read that? And how Russia solved the problem?"

"Yeah, they used a pencil."

"Right, a normal wooden pencil. Just seems like Phillip takes the NASA route almost every time."

— Aaron and Abe don't have a stellar comprehension of history, Primer

A while ago I wanted to run something at a certain exact time when I wasn't going to be around to watch it. And it was a Windows box.

The proper way to schedule something on Windows is with a scheduled task.

For what I wanted to do, this was overkill. I just wanted to run a program at 4:15 PM that day and be done. So I wrote this:

[CmdletBinding()]
Param([DateTime] $At, [String] $Command)
$ts = $At - (Get-Date)
if (0 -gt $ts.Ticks) { Exit }
Write-Verbose ("sleeping until {0}" -f ($At))
Start-Sleep -Milliseconds $ts.TotalMilliseconds
try { Invoke-Expression -Command $Command }
catch { Write-Error $_ }

I saved it to a file, ".\do-at.ps1", and I ran it like so:

.\do-at.ps1 -?
do-at.ps1 [[-At] <datetime>] [[-Command] <string>] [<CommonParameters>]

.\do-at.ps1 -At "4:15 PM" -Command "calc.exe" -Verbose

When you just need a pencil, it's useful.

No comments: