Home Windows scheduled tasks
Post
Cancel

Windows scheduled tasks

sometimes you wanna automate a process like backing up a folder or cleaning up the desktop or some other thing, to do that you can schedule a task to be executed by windows task scheduler.

on linux you can do the same thru either a cron job or airflow.

thru powershell 7

1
Register-ScheduledTask -Action <ACTION U WANNA DO> -Trigger <TRIGGER> -TaskName <TASK NAME>
  • Action: is the action, for example execute a script
  • Trigger: do this action daily @ 12:00AM
  • TaskName: give it a meaningful name

example:

1
Register-ScheduledTask -Action New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-File .\backup-notes.ps1" -Trigger New-ScheduledTaskTrigger -Daily -At 12:00AM -TaskName "BackUpNotesToGitTask"

as you can see this is a monstrosity to type, good thing you can use variables xD

1
2
3
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-File .\backup-notes.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 12:00AM 
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "BackUpNotesToGitTask"

this is simpler and you can make a script outta it.

thru the gui

I’m gonna create a task that would run an exe that i’ve written in rust, which will clean development dependencies for a given directory.

be careful what you run!

  • open it from start
    • step-1
  • create Task
    • step-2
  • Actions -> New
    • step-3
    • step-4
    • Browse to your exe or script u wanna run and give it what argument it needs, in this case just “E:\development\front-end” node-modules gotta go man!
      • step-5
    • give it a scheule and click ok Daily is bad for this, unless u like to keep running npm i
      • step-6
  • there are the 2 tasks we created, the first from the command line and the other from the gui step-7
  • at the defined time the job will run or u can click run step-8

powershell script to backup

what this does is:

  1. get the current path this was executed from
  2. sets the execution policy,
  3. goes to the path my obsidian library lives in
  4. pushes the code to github
  5. sets the location to the directory it was executed from
  6. on error it’s supposed to log it into a file in an adjacent folder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$errorLog = "C:\Windows Tools\myUtilities\ToolLogs\BackUpNotes.txt"
$currentLocation = Get-Location

try {
  Set-ExecutionPolicy RemoteSigned -Scope Process -Force
  Set-Location -Path "$env:USERPROFILE\notes\crimson_library"
  
  git add -A
  git commit -m "From Task Schedular"
  git push

}
catch {
   $_ | Out-File -FilePath $errorLog -Append
}
finally {
  Set-Location -Path $currentLocation
}


This post is licensed under CC BY 4.0 by the author.

on-demand DBMS

Android dev environment