From time to time I find it useful to schedule tasks to run on my machine. I often realize that many people are unaware that windows 2003 has a built in task scheduler; and even more of a rarity for them to be aware it can be managed via the command line. 

Enter SCHTASKS http://support.microsoft.com/kb/814596/

In the past I would crate a batch file to create the schedules; just to make it easy and repeatable. Having the setup separate from the batch file that does the work always bugged me.

The other day I when I found the need to have a task run every five minutes, I did it in powershell.  I thought to myself hey this is powershell, we’ve got some more power here; what if this script could schedule it’s self? And that’s how this idea was born.

When run without parameters it executes normaly.
Specify the -schedule switch to have it schedule itself.
For details on schtasks options see: http://support.microsoft.com/kb/814596/

Selfscheduling.ps1:

param ([switch] $schedule)

if ($schedule) {
$taskname = $myinvocation.mycommand.definition -replace '\W','_'
schtasks /create  /sc MINUTE /MO 5 /tn "$taskname" /tr "powershell -c $($myinvocation.mycommand.definition)"
return;
}

#switch to directory where the script lives
pushd (split-path -parent $myinvocation.mycommand.definition)

#insert useful code here
write-host "Hello World"

popd