Jump to content

Taskplaner/Taskscheduler COM UDF


Allow2010
 Share

Recommended Posts

Hi all,

i needed an UDF for using the Windows Taskplaner / Task Scheduler.

Everything i found was

  • based on at.exe (outdated) or
  • based on schtasks.exe (limited in functionality) or
  • using WMI (which can not see task that were not created with WMI and is also limited)

The only good solution i found was here: http://www.autoit.de/index.php?page=Thread&postID=214517#post214517

But it only had a Create Function.

With my limited knowledge i tried creating more functions and it seems to work quite OK.

You can try it out with TestTaskSchedulerUDF(). WinVista or higher is required.

All feedback is welcome, but please be kind, i do not have much practise and i am well aware that there is room for improvment.

Edit: added new version of the code with more functions:
Edit2: updated UDF fixed bugs
Edit3: added info for multiinst parameter (_TaskCreate)
Edit4: updated UDF (some bugfixes)
Edit5: added version info to UDF, added changes/additions suggested in this thread (_TaskIsEnabled(), _TaskEnable(), _TaskDisable() and $duration for _TaskCreate())
Edit6: added new version that does not use a COM errorhandler (this version can be mixed with other com functions with or without errorhandler, but requires current autoit beta 3.3.9.4 or newer) - see this post for details: (if you do not need other COM routines, there is no need to change from the last version to this one, but all newer version will be without errorhandler...)
Edit7: added version 5.2 with new TaskCreate option $starwhenavailable

Edit8: added version 5.3 fixed versioncompare problems and some typos (now runs with latest beta 3.3.9.22)

Edit9: added version 5.4 (the COM errorhandler is back :-))


As long as there is no feedback this will be the last update...for me it works like it should and i can manage all my tasks just fine!
Keep in Mind that Autoit does not support using more than one ComError Function so be careful if you use other com udfs that need a com errorfunction - this is not a problem when using the taskplanerCOMneh.au3 version (neh=no error handler) No longer true - use lates version with errorhandler


Now we have:

  • Func _TestTaskSchedulerUDF()
  • Func _TaskSchedulerAutostart();check if the schedulerservice is set to autostart
  • Func _TaskIsValidPlatfrom() ;check if os and autoit versions are OK for use with this udf
  • Func _TaskFolderCreate($folder);Create folder - only folders that do not already exist can be created without error
  • Func _TaskFolderDelete($folder);Delete folder - only folders that do exist and that are empty can be deleted without error
  • Func _TaskFolderExists($folder = "");check if a TaskFolder exists
  • Func _TaskExists($taskname, $folder = "");check if a Task exists
  • Func _TaskStop($taskname, $folder = "");stop a task
  • Func _TaskStart($taskname, $folder = "");start a task
  • Func _TaskIsRunning($taskname, $folder = "");check if a Task is running
  • Func _TaskIsEnabled($taskname, $folder = "");check if a Task is enabled
  • Func _TaskEnable($taskname, $folder = "");Enable Task
  • Func _TaskDisable($taskname, $folder = "");Disable Task
  • Func _TaskDelete($taskname, $folder = "");delete an existing task
  • Func _TaskListall($folder = "", $hidden = 1);get a list of all tasks in a given taskfolder (Tasknames only) List is a string with names separeted by "|"
  • Func _TaskCreate($taskname, $TaskDescription, $TriggerEvent, $StartTrigger, $EndTrigger, $DaysOfWeek, $DaysOfMonth, $MonthOfYear, $WeeksOfMonth, $DaysInterval, $Interval, $RepetitionEnabled, $LogonType, $RunLevel, $Username, $Password, $Program, $WorkingDirectory = "", $Arguments = "", $RunOnlyIfNetworkAvailable = True, $active = True, $multiinst = 0, $nobatstart = False, $stoponBat = False, $hidden = False, $idle = False, $WakeToRun = False, $timelimit = "P1D", $priority = 5, $duration="", $StartWhenAvailable = True)

taskplanerCOMneh5.2.zip

taskplanerCOM_neh5.3.zip

taskplanerCOM_5.4.zip

Edited by Allow2010
Link to comment
Share on other sites

as this is very fresh and i could very well need some help to improve it, i think it is no yet ready to be an example-)

>WinVista or higher is required.

>>P.S. I don't have vista so I can't test it

hmm, but you probaly have something newer than Vista? Or are you still running W2000/9x?

Edited by Allow2010
Link to comment
Share on other sites

This page here http://msdn.microsoft.com/en-us/library/windows/desktop/aa381341%28v=VS.85%29.aspx

tells me that i can get a returncode

Return value

If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

but $result = $oFolder.CreateFolder($folder) seems to return

[out] ITaskFolder **ppFolder

so any idea how i can get the return code? Thanks !

Link to comment
Share on other sites

  • Moderators

Allow2010,

Do you want it moved?

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Moderators

Allow2010,

You will get many more hits here - could help you make it even better. :)

M23

Edited by Melba23
Wrong button too soon!

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • 3 months later...

I am impressed with your UDF and I think it is much better than schtasks.exe

I want to create a daily task, which

  • starts at 6:30
  • repeats every 6 hours, for a duration of one day
At the moment I can create a daily task which starts at 6:30, repeats every 6 hours but indefinately. I would like to change that to a duration of one day if possible?

_TaskCreate("Smart-Net\SmartRAS Monitor Script", "Report in info about the Smart-RAS to SNID", 2, "2000-01-01T06:30:00", "", "", "", "", "", 1, "PT6H", True, 1, 0, $username,$password, """"&$app&"""", "", "", False, True,0,True,True,False,False,False,"P3D",5)

EDIT

Have modified the UDF to support $Duration

If $RepetitionEnabled Then
  $oTriggerRepetition = $oTrigger.Repetition()
  $oTriggerRepetition.Interval() = $Interval
  $oTriggerRepetition.Duration() = $Duration
 EndIf

Now I am running this code to do what I need

_TaskCreate("Smart-Net\SmartRAS Monitor Script", "Report in info about the Smart-RAS to SNID", 2, "2000-01-01T06:30:00", "", "", "", "", "", 1, "PT6H","P1D", True, 1, 0, $username,$password, """"&$app&"""", "", "", False, True,0,True,True,False,False,False,"P3D",5)

Thanks for the code, its extremely useful. BTW if others want to modify the code I recommend using powershell script here to enumerate the schedule task objects

Edited by NDog
Link to comment
Share on other sites

Looks like a useful UDF Allow2010. Thanks ;)

A very small suggestion: The _TaskCreate function has a dayof month parameter which has to be some power of 2. It would be easier (for me at least) if this parameter were just the actual day of the month. To keep it compatible with previous versions you could say that if a negative value is used it means the actual day number (1 - 31). Use -32 for "last day". Then in the function you could have

if $DaysOfMonth < 0 then
 $DaysOfMonth = 2^(-$DaysOfMonth - 1)
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

  • 4 weeks later...

Just came across this today and have to say very impressive. Thanks for posting it. There is room for improvement e.g. _TaskSchedulerAutostart() can be consolidated into one line or three if you count Func and EndFunc.

Func _TaskSchedulerAutostart()
    Return RegRead("HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSchedule", "Start") > 0 ; Returns True or False.
EndFunc   ;==>_TaskSchedulerAutostart
Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 1 month later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...